﻿using BaseUi.Device;
using BaseUi.Models;
using BaseUi.ViewModels;
using HandyControl.Controls;
using HandyControl.Tools.Extension;
using LiveCharts;
using MiniExcelLibs;
using Newtonsoft.Json.Linq;
using Ping9719.DeviceCommunication;
using Ping9719.DeviceCommunication.Clients.PLC;
using Ping9719.WpfEx;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.TextFormatting;
using Win32;
using static BaseUi.Db.JoggleModel;
using static System.Windows.Forms.AxHost;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskbarClock;

namespace BaseUi.ViewModel
{
    public class HomeViewModel : BindableBase
    {
        public ImageBoxView image { get; set; }

        public ImageListenerView image1 { get; set; }
        public ImageListenerView image2 { get; set; }
        public ImageListenerView image3 { get; set; }
        public ImageListenerView image4 { get; set; }
        /// <summary>
        /// 4个位置上是否有料
        /// </summary>
        int[] textnum = new[] { 0, 0, 0, 0 };
        /// <summary>
        /// 4个位置上的OKNG情况
        /// </summary>
        string[] textokng = new[] { "no", "no", "no", "no" };
        /// <summary>
        /// 4个位置上的最终结果
        /// </summary>
        string[] textend = new[] { "", "", "", "" };
        /// <summary>
        /// 转盘方向 1为正向（1.2在外）2为反向
        /// </summary>
        int direction = 0;
        /// <summary>
        /// 下压气缸
        /// </summary>
        bool cylinder = false;
        /// <summary>
        /// 启动方式
        /// </summary>
        public int runstart = 0;
        /// <summary>
        /// 启动旋转方向
        /// </summary>
        public int way = 0;
        /// <summary>
        /// 转盘状态
        /// </summary>
        public bool directioning = false;
        /// <summary>
        /// 是否启动测试
        /// </summary>
        public bool Working = false;
        public bool needchange = true;
        /// <summary>
        /// 线程是否结束
        /// </summary>
        public bool iscolll = true;

        public string type="";


        public int error = 0;

        /// <summary>
        /// 视觉重测次数
        /// </summary>
        public int visnum = 2;

        private Task[] woektasks = new Task[2];
        //Task woekstart = new Task;
        private Task[] task1 = new Task[2];
        private Task[] task2 = new Task[2];
        private Task[] task3 = new Task[2];
        private Task[] task4 = new Task[2];

        CancellationTokenSource cancellationToken = null;//停止
        ManualResetEvent manualReset = null;//暂停、继续
        WarnInfoContainer WarnInfo = new WarnInfoContainer();//警告、错误等信息
        /// <summary>
        /// 有按钮
        /// </summary>
        private bool butthave_ = false;
        public bool butthave { get => butthave_; set { SetProperty(ref butthave_, value); } }
        /// <summary>
        /// 无按钮
        /// </summary>
        private bool buttno_ = false;
        public bool buttno { get => buttno_; set { SetProperty(ref buttno_, value); } }
        #region 页面
        private string text1_ = "等待";
        public string text1 { get => text1_; set { SetProperty(ref text1_, value); } }
        private string text2_ = "等待";
        public string text2 { get => text2_; set { SetProperty(ref text2_, value); } }
        private string text3_ = "等待";
        public string text3 { get => text3_; set { SetProperty(ref text3_, value); } }
        private string text4_ = "等待";
        public string text4 { get => text4_; set { SetProperty(ref text4_, value); } }
        private Brush ZB1_ = Brushes.Gainsboro;
        public Brush ZB1 { get => ZB1_; set { SetProperty(ref ZB1_, value); } }
        private Brush ZB2_ = Brushes.Gainsboro;
        public Brush ZB2 { get => ZB2_; set { SetProperty(ref ZB2_, value); } }
        private Brush ZB3_ = Brushes.Gainsboro;
        public Brush ZB3 { get => ZB3_; set { SetProperty(ref ZB3_, value); } }
        private Brush ZB4_ = Brushes.Gainsboro;
        public Brush ZB4 { get => ZB4_; set { SetProperty(ref ZB4_, value); } }

        public void imgchange()
        {
            image4.viewModel.ImageSource = image1.viewModel.ImageSource;
            image3.viewModel.ImageSource = image2.viewModel.ImageSource;
            image1.viewModel.ImageSource = null;
            image2.viewModel.ImageSource = null;
        }
        public void imgstart()
        {
            image4.viewModel.ImageSource = null;
            image3.viewModel.ImageSource = null;
            image1.viewModel.ImageSource = null;
            image2.viewModel.ImageSource = null;
        }
        public void Uistart(string msg)
        {
            Brush temporaryBrush;
            string temporarytext;
            if (msg == "初始化成功")
            {
                temporaryBrush = Brushes.SlateGray;
                temporarytext = "初始化成功";
            }
            else
            {
                temporaryBrush = Brushes.Crimson;
                temporarytext = msg;
            }
            ZB1 = temporaryBrush;
            ZB2 = temporaryBrush;
            ZB3 = temporaryBrush;
            ZB4 = temporaryBrush;
            text1 = temporarytext;
            text2 = temporarytext;
            text3 = temporarytext;
            text4 = temporarytext;
            if (direction == 1)
            {
                if (LocalFile.Config.Block[0])
                {
                    text1 = "1号测试位屏蔽";
                    ZB1 = Brushes.Black;
                }
                if (LocalFile.Config.Block[1])
                {
                    text2 = "2号测试位屏蔽";
                    ZB2 = Brushes.Black;
                }
                if (LocalFile.Config.Block[2])
                {
                    text3 = "3号测试位屏蔽";
                    ZB3 = Brushes.Black;
                }
                if (LocalFile.Config.Block[3])
                {
                    text4 = "4号测试位屏蔽";
                    ZB4 = Brushes.Black;
                }
            }
            else
            {

                if (LocalFile.Config.Block[0])
                {
                    text3 = "1号测试位屏蔽";
                    ZB3 = Brushes.Black;
                }
                if (LocalFile.Config.Block[1])
                {
                    text4 = "2号测试位屏蔽";
                    ZB4 = Brushes.Black;
                }
                if (LocalFile.Config.Block[2])
                {
                    text1 = "3号测试位屏蔽";
                    ZB1 = Brushes.Black;
                }
                if (LocalFile.Config.Block[3])
                {
                    text2 = "4号测试位屏蔽";
                    ZB2 = Brushes.Black;
                }
            }
        }

        /// <summary>
        /// 气缸到位后将页面刷新
        /// </summary>
        public void UiChange()
        {
            lock (this)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Brush temporaryBrush;
                    string temporarytext;

                    temporaryBrush = ZB3.Clone();
                    ZB3 = ZB1;
                    ZB1 = temporaryBrush;
                    temporarytext = text3.Clone().ToString();
                    text3 = text1;
                    text1 = temporarytext;

                    temporaryBrush = ZB4.Clone();
                    ZB4 = ZB2;
                    ZB2 = temporaryBrush;
                    temporarytext = text4.Clone().ToString();
                    text4 = text2;
                    text2 = temporarytext;
                    //if (text2==text4)
                    //{

                    //}
                    //if (true)
                    //{

                    //}
                });
            }
        }
        /// <summary>
        /// 单个状态刷新
        /// </summary>
        public void Uiupnew(int v, string msg)
        {
            lock (this)
            {
                Brush temporaryBrush;
                string temporarytext;
                if (textnum[v] == 1)
                {
                    if (textokng[v] == "no")
                    {
                        temporarytext = (v + 1) + $"号测试位{msg}";
                        temporaryBrush = Brushes.DarkTurquoise;
                    }
                    else if (textokng[v] == "okend")
                    {
                        temporarytext = (v + 1) + "号测试位成功";
                        temporaryBrush = Brushes.ForestGreen;
                    }
                    else if (textokng[v] == ("ok"))
                    {
                        temporarytext = (v + 1) + $"号测试位{msg}测试中";
                        temporaryBrush = Brushes.DarkTurquoise;
                    }
                    else
                    {
                        string[] mvg = textokng[v].Split(':');
                        temporarytext = (v + 1) + $"号测试位{mvg[0]}";
                        temporaryBrush = Brushes.Crimson;
                    }
                }
                else if (textnum[v] == 0)
                {
                    temporarytext = (v + 1) + "号测试位无料";
                    temporaryBrush = Brushes.Gainsboro;
                }
                else
                {
                    temporarytext = (v + 1) + "号测试位异常";
                    temporaryBrush = Brushes.Crimson;
                }
                if (LocalFile.Config.Block[v])
                {
                    temporarytext = (v + 1) + $"号测试位屏蔽";
                    temporaryBrush = Brushes.Black;
                }
                if (direction==1)
                {
                    if (v == 0)
                    {
                        text1 = temporarytext;
                        ZB1 = temporaryBrush;
                    }
                    else if (v == 1)
                    {
                        text2 = temporarytext;
                        ZB2 = temporaryBrush;
                    }
                    else if (v == 2)
                    {
                        text3 = temporarytext;
                        ZB3 = temporaryBrush;
                    }
                    else if (v == 3)
                    {
                        text4 = temporarytext;
                        ZB4 = temporaryBrush;
                    }
                }
                else
                {
                    if (v == 0)
                    {
                        text3 = temporarytext;
                        ZB3 = temporaryBrush;
                    }
                    else if (v == 1)
                    {
                        text4 = temporarytext;
                        ZB4 = temporaryBrush;
                    }
                    else if (v == 2)
                    {
                        text1 = temporarytext;
                        ZB1 = temporaryBrush;
                    }
                    else if (v == 3)
                    {
                        text2 = temporarytext;
                        ZB2 = temporaryBrush;
                    }
                }
            }
        }
        /// <summary>
        /// 单个状态刷新人工确认
        /// </summary>
        public void PeopleUiupnew(int v)
        {
            lock (this)
            {
                Brush temporaryBrush;
                temporaryBrush = Brushes.ForestGreen;
                if (v == 0)
                {
                    ZB1 = temporaryBrush;
                }
                else
                {
                    ZB2 = temporaryBrush;
                }
            }
        }
        //public void SetUi()
        //{
        //    if (direction == 1)
        //    {
        //        if (textnum[0] == 1)
        //        {
        //            if (textokng[0] == "no")
        //            {
        //                text1 = "1号未测";
        //                ZB1 = Brushes.DarkTurquoise;
        //            }
        //            else if (textokng[0] == "okend")
        //            {
        //                text1 = "1号OK";
        //                ZB1 = Brushes.ForestGreen;
        //            }
        //            else if(textokng[0].Contains("ok"))
        //            {
        //                text1 = "1号测试中";
        //                ZB1 = Brushes.DarkTurquoise;
        //            }
        //            else 
        //            {
        //                text1 = "1号失败";
        //                ZB1 = Brushes.Crimson;
        //            }
        //        }
        //        else if(textnum[0] == 0)
        //        {
        //            text1 = "1号无料";
        //            ZB1 = Brushes.Gainsboro;
        //        }
        //        else
        //        {
        //            text1 = "1号异常";
        //            ZB1 = Brushes.Crimson;
        //        }
        //        if (textnum[1] == 1)
        //        {
        //            if (textokng[1] == "no")
        //            {
        //                text2 = "2号未测";
        //                ZB2 = Brushes.DarkTurquoise;
        //            }
        //            else if (textokng[1] == "okend")
        //            {
        //                text2 = "2号OK";
        //                ZB2 = Brushes.ForestGreen;
        //            }
        //            else if (textokng[1].Contains("ok"))
        //            {
        //                text2 = "2号测试中";
        //                ZB2 = Brushes.DarkTurquoise;
        //            }
        //            else
        //            {
        //                text2 = "2号失败";
        //                ZB2 = Brushes.Crimson;
        //            }
        //        }
        //        else if(textnum[1] == 0)
        //        {
        //            text2 = "2号无料";
        //            ZB2 = Brushes.Gainsboro;
        //        }
        //        else
        //        {
        //            text2 = "2号感应异常";
        //            ZB2 = Brushes.Crimson;
        //        }

        //        if (textnum[2] == 1)
        //        {
        //            if (textokng[2] == "no")
        //            {
        //                text3 = "3号未测";
        //                ZB3 = Brushes.DarkTurquoise;
        //            }
        //            else if (textokng[2] == "okend")
        //            {
        //                text3 = "3号OK";
        //                ZB3 = Brushes.ForestGreen;
        //            }
        //            else if (textokng[2].Contains("ok"))
        //            {
        //                text3 = "3号测试中";
        //                ZB3 = Brushes.DarkTurquoise;
        //            }
        //            else
        //            {
        //                text3 = "3号失败";
        //                ZB3 = Brushes.Crimson;
        //            }
        //        }
        //        else if(textnum[2] == 0)
        //        {
        //            text3 = "3号无料";
        //            ZB3 = Brushes.Gainsboro;
        //        }
        //        else
        //        {
        //            text3 = "3号感应异常";
        //            ZB3 = Brushes.Crimson;
        //        }

        //        if (textnum[3] == 1)
        //        {
        //            if (textokng[3] == "no")
        //            {
        //                text4 = "4号未测";
        //                ZB4 = Brushes.DarkTurquoise;
        //            }
        //            else if (textokng[3] == "okend")
        //            {
        //                text4 = "4号OK";
        //                ZB4 = Brushes.ForestGreen;
        //            }
        //            else if (textokng[3].Contains("ok"))
        //            {
        //                text4 = "4号测试中";
        //                ZB4 = Brushes.DarkTurquoise;
        //            }
        //            else
        //            {
        //                text4 = "4号失败";
        //                ZB4 = Brushes.Crimson;
        //            }
        //        }
        //        else if(textnum[3] ==0)
        //        {
        //            text4 = "4号无料";
        //            ZB4 = Brushes.Gainsboro;
        //        }
        //        else
        //        {
        //            text4 = "4号感应异常";
        //            ZB4 = Brushes.Crimson;
        //        }

        //    }
        //    else if (direction == 2)
        //    {
        //        if (textnum[2] == 1)
        //        {
        //            if (textokng[2] == "no")
        //            {
        //                text1 = "3号未测";
        //                ZB1 = Brushes.DarkTurquoise;
        //            }
        //            else if (textokng[2] == "okend")
        //            {
        //                text1 = "3号OK";
        //                ZB1 = Brushes.ForestGreen;
        //            }
        //            else if (textokng[2].Contains("ok"))
        //            {
        //                text1 = "3号测试中";
        //                ZB1 = Brushes.DarkTurquoise;
        //            }
        //            else
        //            {
        //                text1 = "3号失败";
        //                ZB1 = Brushes.Crimson;
        //            }
        //        }
        //        else if(textnum[2] ==0)
        //        {
        //            text1 = "3号无料";
        //            ZB1 = Brushes.Gainsboro;
        //        }
        //        else
        //        {
        //            text1 = "3号感应异常";
        //            ZB1 = Brushes.Crimson;
        //        }
        //        if (textnum[3] == 1)
        //        {
        //            if (textokng[3] == "no")
        //            {
        //                text2 = "4号未测";
        //                ZB2 = Brushes.DarkTurquoise;
        //            }
        //            else if (textokng[3] == "okend")
        //            {
        //                text2 = "4号OK";
        //                ZB2 = Brushes.ForestGreen;
        //            }

        //            else if (textokng[3].Contains("ok"))
        //            {
        //                text2 = "4号测试中";
        //                ZB2 = Brushes.DarkTurquoise;
        //            }
        //            else
        //            {
        //                text2 = "4号失败";
        //                ZB2 = Brushes.Crimson;
        //            }
        //        }
        //        else if(textnum[3] ==0)
        //        {
        //            text2 = "4号无料";
        //            ZB2 = Brushes.Gainsboro;
        //        }
        //        else
        //        {
        //            text2 = "4号感应异常";
        //            ZB2 = Brushes.Crimson;
        //        }
        //        if (textnum[0] == 1)
        //        {
        //            if (textokng[0] == "no")
        //            {
        //                text3 = "1号未测";
        //                ZB3 = Brushes.DarkTurquoise;
        //            }
        //            else if (textokng[0] == "okend")
        //            {
        //                text3 = "1号OK";
        //                ZB3 = Brushes.ForestGreen;
        //            }
        //            else if (textokng[0].Contains("ok"))
        //            {
        //                text3 = "1号测试中";
        //                ZB3 = Brushes.DarkTurquoise;
        //            }
        //            else
        //            {
        //                text3 = "1号失败";
        //                ZB3 = Brushes.Crimson;
        //            }
        //        }
        //        else if(textnum[0] ==0)
        //        {
        //            text3 = "1号无料";
        //            ZB3 = Brushes.Gainsboro;
        //        }
        //        else
        //        {
        //            text3 = "1号感应异常";
        //            ZB3 = Brushes.Crimson;
        //        }
        //        if (textnum[1] == 1)
        //        {
        //            if (textokng[1] == "no")
        //            {
        //                text4 = "2号未测";
        //                ZB4 = Brushes.DarkTurquoise;
        //            }
        //            else if (textokng[1] == "okend")
        //            {
        //                text4 = "2号OK";
        //                ZB4 = Brushes.ForestGreen;
        //            }
        //            else if (textokng[1].Contains("ok"))
        //            {
        //                text4 = "2号测试中";
        //                ZB4 = Brushes.DarkTurquoise;
        //            }
        //            else
        //            {
        //                text4 = "2号失败";
        //                ZB4 = Brushes.Crimson;
        //            }
        //        }
        //        else if (textnum[1] == 0)
        //        {
        //            text4 = "2号无料";
        //            ZB4 = Brushes.Gainsboro;
        //        }
        //        else
        //        {
        //            text4 = "2号感应异常";
        //            ZB4 = Brushes.Crimson;
        //        }
        //    }
        //    else
        //    {
        //        text1 = "null";
        //        text2 = "null";
        //        text3 = "null";
        //        text4 = "null";
        //        ZB1 = Brushes.Gainsboro;
        //        ZB2 = Brushes.Gainsboro;
        //        ZB3 = Brushes.Gainsboro;
        //        ZB4 = Brushes.Gainsboro;
        //    }
        //}
        #endregion
        #region 绑定
        private string textErr;
        /// <summary>
        /// 错误文本
        /// </summary>
        public string TextErr { get => textErr; set { SetProperty(ref textErr, value); } }
        //所有信息
        List<ErrInfo> errInfos = new List<ErrInfo>();
        struct ErrInfo
        {
            public bool IsTemp;//临时
            public string Name;//名称、错误组名
            public string ErrText;//错误信息
        }
        public ICommand ClearTextInfoCommand { get => new DelegateCommand(ClearTextInfo); }
        /// <summary>
        /// 清除信息文本
        /// </summary>
        public void ClearTextInfo()
        {
            TextBoxLog.ClearLog();
        }
        public ICommand ClearTextErrCommand { get => new DelegateCommand(ClearTextErr); }
        /// <summary>
        /// 清除全部错误文本
        /// </summary>
        public void ClearTextErr()
        {
            errInfos.Clear();
            UpdataErrToUi();
            //WarnInfo.RemoveAll(WarnInfoType.AlwayWarn);
        }
        /// <summary>
        /// 添加一个常驻错误
        /// </summary>
        /// <param name="err"></param>
        public void AddTextErr(string err)
        {
            AddTextErr(new string[] { err });
        }

        /// <summary>
        /// 添加一个常驻错误
        /// </summary>
        /// <param name="err"></param>
        public void AddTextErr(string name, string err)
        {
            AddTextErr(name, new string[] { err });
        }

        /// <summary>
        /// 添加一个常驻错误
        /// </summary>
        /// <param name="err"></param>
        public void AddTextErr(IEnumerable<string> errs)
        {
            AddTextErr(string.Empty, errs);
        }

        /// <summary>
        /// 添加一个常驻错误
        /// </summary>
        /// <param name="err"></param>
        public void AddTextErr(string name, IEnumerable<string> errs)
        {
            if (errs == null)
                return;

            foreach (var item in errs)
            {
                ErrInfo errInfo = new ErrInfo();
                errInfo.IsTemp = false;
                errInfo.Name = name;
                errInfo.ErrText = item;
                errInfos.Add(errInfo);
            }

            UpdataErrToUi();
        }

        /// <summary>
        /// 添加临时错误
        /// </summary>
        /// <param name="err"></param>
        public void AddTempTextErr(IEnumerable<string> errs)
        {
            AddTempTextErr(string.Empty, errs);
        }

        /// <summary>
        /// 添加临时错误
        /// </summary>
        /// <param name="err"></param>
        public void AddTempTextErr(string name, IEnumerable<string> errs)
        {
            errInfos.RemoveAll(i => i.Name == name);

            if (errs != null && errs.Any())
                foreach (var item in errs)
                {
                    ErrInfo errInfo = new ErrInfo();
                    errInfo.IsTemp = true;
                    errInfo.Name = name;
                    errInfo.ErrText = item;
                    errInfos.Add(errInfo);
                }

            UpdataErrToUi();
        }

        //更新错误到界面
        private void UpdataErrToUi()
        {
            TextErr = string.Join(Environment.NewLine, errInfos?.OrderBy(o => (o.Name, o.IsTemp))?.Select(o => string.IsNullOrEmpty(o.Name) ? o.ErrText : $"[{o.Name}]{o.ErrText}") ?? new string[] { });
        }
        #endregion

        #region 页面加载时任务
        /// <summary>
        /// 页面第一次加载时执行的任务
        /// </summary>
        public void LoadTask()
        {
            //注册警告事件
            WarnInfo.WarnInfoChanged += (all, add, rem) =>
            {
                //界面展示
                TextErr = string.Join(Environment.NewLine, all.OrderBy(o => (o.WarnType, o.Source, o.Text)));
                //日志记录
                Logs.Write(add.Concat(rem).Select(o => o.ToString()), LogsType.Warning);
                //数据库保存
                //if (WarnInfoDb.IsEnabled)
                //{
                //    WarnInfoDb.db.Insertable(WarnInfoItemDb.GetList(add)).ExecuteCommand();
                //    WarnInfoDb.db.Updateable(WarnInfoItemDb.GetList(rem)).ExecuteCommand();
                //}
            };
            //LocalStatic.Electric.s();
            Task.Run(() =>
            {
                TextBoxLog.AddLog("状态检测");
                way = 0;
                var dd = LocalStatic.Electric.Readsentled(500, PortModel.LED1ok, 0, LocalFile.Config.Address);
                if (!dd.IsSucceed)
                {
                    TextBoxLog.AddLog("1号绿灯复位通信失败");
                }
                dd = LocalStatic.Electric.Readsentled(500, PortModel.LED1ng, 0, LocalFile.Config.Address); if (!dd.IsSucceed)
                {
                    TextBoxLog.AddLog("1号红灯复位通信失败");
                }
                dd = LocalStatic.Electric.Readsentled(500, PortModel.LED2ok, 0, LocalFile.Config.Address); if (!dd.IsSucceed)
                {
                    TextBoxLog.AddLog("2号绿灯复位通信失败");
                }
                dd = LocalStatic.Electric.Readsentled(500, PortModel.LED2ng, 0, LocalFile.Config.Address); if (!dd.IsSucceed)
                {
                    TextBoxLog.AddLog("2号红灯复位通信失败");
                }
                string retul = Statedetection();//初始化是否成功
                if (retul != "OK")
                {
                    TextBoxLog.AddLog(retul);
                    //Growl.Warning("未满足运行条件，请初始化");
                    TextBoxLog.AddLog("未满足运行条件，请先选产品类型再初始化");
                    return;
                }

                TextBoxLog.AddLog("满足运行条件，请先选产品类型再初始化");
                //Start();
                //Vision(0);
                //Load();

                //TextBoxLog.AddLog("满足运行条件，请放置产品");
                //Task.Run(Circulate);

            });

            //Task.Run(Circulate);
            //Trial();
            //Task.Run(PlcErrListen);
        }
        /// <summary>
        /// 测试通信
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void Trial()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 根据Excel里面的内容监听plc错误信息
        /// </summary>
        async void PlcErrListen()
        {
            //Excel解析的错误格式
            var excelErrAll = ExcelDeviceAlarmModel.GetDatas(LocalFile.PlcDotPath);
            while (true)
            {
                //需要将null替换为设备，如“LocalStatic.Plc”，并去里面解开注释
                var excelErr = ExcelDeviceAlarmModel.ReadPlcAlarm(excelErrAll, null);

                WarnInfo.AddOrUpdate(excelErr.Select(o => new WarnInfoItem()
                {
                    Text = o.名称,
                    WarnType = WarnInfoType.WhileWarn,
                    Level = o.级别,
                    Solution = o.解决方式
                }), "PLC");

                await Task.Delay(500);
            }
        }
        #endregion

        #region 业务

        private RunState runState = RunState.Stop;
        /// <summary>
        /// 运行状态
        /// </summary>
        public RunState RunState { get => runState; set { SetProperty(ref runState, value); } }

        public ICommand RunStateClickCommand { get => new DelegateCommand<RunStateButtonClick>(RunStateClick); }
        /// <summary>
        /// 运行状态
        /// </summary>
        public void RunStateClick(RunStateButtonClick clickrunState)
        {
            if (clickrunState == RunStateButtonClick.Start)
            {

                //BarChartView.viewModel.AddNg(1);
                //TextBoxLog.AddLog("点击开始");
                way = 0;
                if (RunState != RunState.Stop)
                {
                    TextBoxLog.AddLog("非停止状态禁止初始化");
                    return;
                    //Stop();
                }
                //if (RunState != RunState.Stop) {
                //    Stop();
                //}
                Start();
                var dd = LocalStatic.Electric.Readsentled(500, PortModel.LED1ok, 0, LocalFile.Config.Address);
                if (!dd.IsSucceed)
                {
                    TextBoxLog.AddLog("1号绿灯复位通信失败");
                }
                dd = LocalStatic.Electric.Readsentled(500, PortModel.LED1ng, 0, LocalFile.Config.Address); if (!dd.IsSucceed)
                {
                    TextBoxLog.AddLog("1号红灯复位通信失败");
                }
                dd = LocalStatic.Electric.Readsentled(500, PortModel.LED2ok, 0, LocalFile.Config.Address); if (!dd.IsSucceed)
                {
                    TextBoxLog.AddLog("2号绿灯复位通信失败");
                }
                dd = LocalStatic.Electric.Readsentled(500, PortModel.LED2ng, 0, LocalFile.Config.Address); if (!dd.IsSucceed)
                {
                    TextBoxLog.AddLog("2号红灯复位通信失败");
                }
                //initial();
                //Task.Run( initial);
                //Task.WaitAll(Task.Run(initial));
                //Task.WaitAll(Task.Run(initial));
                //Load();
                if (RunState == RunState.Run)
                {
                    //TextBoxLog.AddLog("状态检测完毕，可以运行");
                    Task.Run(Circulate);
                }
                else
                {
                    TextBoxLog.AddLog("状态检测完毕，未满足运行条件");
                }
            }
            else if (clickrunState == RunStateButtonClick.Pause)
            {
                TextBoxLog.AddLog("点击暂停");
                Pause();
            }
            else if (clickrunState == RunStateButtonClick.Continue)
            {
                if (MainWindow2.viewModel.Switch)
                {
                    TextBoxLog.AddLog("开关箱触发中");
                    return;
                }
                if (MainWindow2.viewModel.Raster)
                {
                    if (HomeView.viewModel.directioning == true)
                    {
                        TextBoxLog.AddLog("光栅触发中");
                        return;
                    }
                }
                if (MainWindow2.viewModel.Scram)
                {
                    TextBoxLog.AddLog("急停按钮急停中");
                    return;
                }
                TextBoxLog.AddLog("点击继续");
                string retul = prepose();
                if (retul != "OK")
                {
                    TextBoxLog.AddLog(retul);
                    return;
                }
                if (way == 1)
                {
                    var ddd = LocalStatic.Electric.Readsentrelay(500, PortModel.Rotate1, PortModel.Rotate2, LocalFile.Config.Address);
                    if (!ddd.IsSucceed)
                    {
                        TextBoxLog.AddLog("旋转气缸失败" + ddd.Err);
                        return;
                    }
                }
                else if (way == 2)
                {
                    var ddd = LocalStatic.Electric.Readsentrelay(500, PortModel.Rotate2, PortModel.Rotate1, LocalFile.Config.Address);
                    if (!ddd.IsSucceed)
                    {
                        TextBoxLog.AddLog("旋转气缸失败" + ddd.Err);
                        return;
                    }
                }
                Continue();
            }
            else if (clickrunState == RunStateButtonClick.Stop)
            {
                TextBoxLog.AddLog("点击停止");
                Stop();
            }
            else if (clickrunState == RunStateButtonClick.Rset)
            {
                if (RunState != RunState.Stop)
                {
                    TextBoxLog.AddLog("停止状态才能将测试板复位");
                    Growl.Info("停止状态才能将测试板复位");
                    return;
                }
                Reset();
            }
        }
        #region
        /// <summary>
        /// 获取初始信息判断状态 
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        //private void Load()
        //{
        //int number = 0;
        //int dian = 0;
        //while (true)
        //{
        //    Thread.Sleep(100);
        //    number = number + 1;
        //    if (number>5) {
        //        break;

        //    }
        //    dian = getfreque();
        //    if (dian != -1)
        //    {
        //        break;
        //    }
        //}
        //if (dian != 1 && dian != 2)
        //{
        //    TextBoxLog.AddLog("旋转气缸到位通信失败" + dian + "（-1通信失败，0两边都没有到位信号，1正向，2反向，3两边都有到位信息）");
        //    if (RunState != RunState.Stop) { Stop(); }
        //    return;
        //}
        //else
        //{
        //    direction = dian;
        //}
        //directioning = false;
        //string retul = getjack();
        //if (retul != "OK")
        //{
        //    TextBoxLog.AddLog(retul);
        //    if (RunState != RunState.Stop) { Stop(); }
        //    return;
        //}
        ////retul = "";
        ////for (int i = 0; i < 4; i++)
        ////{
        ////    if (textnum[i] == 1)
        ////    {
        ////        TextBoxLog.AddLog("测试" + (i+1).ToString() + "箱有产品");
        ////        retul = "NG";
        ////    }
        ////    else if (textnum[i] != 0&& textnum[i] !=1)
        ////    {
        ////        TextBoxLog.AddLog("测试" + (i + 1).ToString() + "箱感应值异常");
        ////        retul = "NG";
        ////    }
        ////    textokng[i] = "no";
        ////}
        ////if (RunState != RunState.Stop&& retul!="") { Stop(); }
        //return;
        ////SetUi(); 

        //}
        /// <summary>
        /// 初始化（使状态回到可以运行的状态）
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void initial()
        {
            direction = 1;
            string retul = "";
            retul = getjack();
            if (retul != "OK")
            {
                TextBoxLog.AddLog(retul);
                if (RunState == RunState.Run)
                {
                    Stop();
                }
                return;
            }

            retul = satisfy();
            if (retul != "OK")
            {
                TextBoxLog.AddLog(retul);
                if (RunState == RunState.Run)
                {
                    Stop();
                }
                return;
            }

            TextBoxLog.AddLog("转盘安全可转动");
            retul = prepose();
            if (retul != "OK")
            {
                TextBoxLog.AddLog(retul);
                if (RunState == RunState.Run)
                {
                    Stop();
                }
                return;
            }
            retul = turn(0);
            if (retul != "OK")
            {
                TextBoxLog.AddLog(retul);
                if (RunState == RunState.Run)
                {
                    Stop();
                }
                return;
            }
            Thread.Sleep(500);
            reach();
            Changeled(0);
            Changeled(1);
            Jack();
            Changend();
            Thread.Sleep(1000);
            retul = prepose();
            if (retul != "OK")
            {
                TextBoxLog.AddLog(retul);
                if (RunState == RunState.Run)
                {
                    Stop();
                }
                return;
            }
            retul = turn(1);
            if (retul != "OK")
            {
                TextBoxLog.AddLog(retul);
                if (RunState == RunState.Run)
                {
                    Stop();
                }
                return;
            }
            Thread.Sleep(500);
            reach();
            Changeled(0);
            Changeled(1);
            Jack();
            Changend();
        }
        #endregion
        /// <summary>
        /// 获取当前旋转气缸状态（-1通信失败，0两边都没有到位信号，1正向，2反向，3两边都有到位信息）
        /// </summary>
        /// <returns></returns>
        private int getfreque()
        {
            Thread.Sleep(500);
            if (!MainWindow2.viewModel.ischengg)
            {
                return -1;
            }
            string dian = MainWindow2.viewModel.msg[0] + " " + MainWindow2.viewModel.msg[1] + " ";
            if (dian == "00 01 ")
            {
                return 2;
            }
            else if (dian == "01 00 ")
            {

                return 1;
            }
            else if (dian == "00 00 ")
            {

                return 0;
            }
            else
            {

                return 3;
            }
        }
        /// <summary>
        /// 测试板检测是否有物料(有料需要通过)
        /// </summary>
        /// <returns></returns>
        private string getjack()
        {
            string retul = "";
            for (int i = 0; i < 4; i++)
            {
                textokng[i] = "no";
                var gettext = LocalStatic.Test[0 + i].ReadSensor();
                if (!gettext.IsSucceed)
                {
                    Thread.Sleep(50);
                    gettext = LocalStatic.Test[0 + i].ReadSensor();
                    if (!gettext.IsSucceed)
                    {
                        textnum[i] = 2;
                        retul = retul + (i + 1).ToString() + $"号测试位{LocalStatic.Test[0 + i].name}通信失败！\r\n";
                    }
                }
                else
                {
                    int getnumber = int.Parse(gettext.Value);
                    if (getnumber < LocalFile.Config.DSensor[i])
                    {
                        textnum[i] = 1;
                        retul = retul + (i + 1).ToString() + "号测试位有料！\r\n";
                    }
                    else if (getnumber > LocalFile.Config.USensor[i])
                    {
                        textnum[i] = 0;
                    }
                    else
                    {
                        textnum[i] = 2;
                        retul = retul + (i + 1).ToString() + "号测试位未按压到位或方向错误请按压或拿开！\r\n";
                    }
                }
            }
            if (retul == "") { return "OK"; }
            else { return retul; }
        }
        private void Reset()
        {
            //var dd = LocalStatic.Electric.Readsentrelay(500, PortModel.Retul, new List<int>(), LocalFile.Config.Address);
            //if (!dd.IsSucceed)
            //{
            //    dd = LocalStatic.Electric.Readsentrelay(500, PortModel.Retul, new List<int>(), LocalFile.Config.Address);
            //    if (!dd.IsSucceed)
            //    {
            //        TextBoxLog.AddLog($"测试板复位失败：闭合：{dd.Err}");
            //        return;
            //    }
            //}
            //TextBoxLog.AddLog($"测试板复位闭合成功");
            //Thread.Sleep(300);
            var dd1 = LocalStatic.Electric.Readsentrelay(500, new List<int>(), PortModel.Retul, LocalFile.Config.Address);
            if (!dd1.IsSucceed)
            {
                dd1 = LocalStatic.Electric.Readsentrelay(500, new List<int>(), PortModel.Retul, LocalFile.Config.Address);
                if (!dd1.IsSucceed)
                {
                    TextBoxLog.AddLog($"测试板复位失败：断开：{dd1.Err}");
                    return;
                }
            }
            TextBoxLog.AddLog($"测试板复位断开成功");
            Thread.Sleep(5000);
            var dd = LocalStatic.Electric.Readsentrelay(500, PortModel.Retul, new List<int>(), LocalFile.Config.Address);
            if (!dd.IsSucceed)
            {
                dd = LocalStatic.Electric.Readsentrelay(500, PortModel.Retul, new List<int>(), LocalFile.Config.Address);
                if (!dd.IsSucceed)
                {
                    TextBoxLog.AddLog($"测试板复位失败：闭合：{dd.Err}");
                    return;
                }
            }
            TextBoxLog.AddLog($"测试板复位闭合成功");
            TextBoxLog.AddLog($"测试板复位成功");
        }
            /// <summary>
            /// 循环线程
            /// </summary>
            /// <exception cref="NotImplementedException"></exception>
            private void Circulate()
        {
            try
            {
                type = "";
                error = 0;
                iscolll = false;
                //var dd = LocalStatic.Electric.Readsentrelay(500, PortModel.Retul,  new List<int>(), LocalFile.Config.Address);
                //if (!dd.IsSucceed)
                //{
                //    dd = LocalStatic.Electric.Readsentrelay(500, PortModel.Retul, new List<int>(), LocalFile.Config.Address);
                //    if (!dd.IsSucceed)
                //    {
                //        TextBoxLog.AddLog($"测试板复位失败：闭合：{dd.Err}");
                //    }
                //}Thread.Sleep(300);
                //dd = LocalStatic.Electric.Readsentrelay(500, new List<int>(), PortModel.Retul, LocalFile.Config.Address);
                //if (!dd.IsSucceed)
                //{
                //    dd = LocalStatic.Electric.Readsentrelay(500, new List<int>(), PortModel.Retul, LocalFile.Config.Address);
                //    if (!dd.IsSucceed)
                //    {
                //        TextBoxLog.AddLog($"测试板复位失败：断开：{dd.Err}");
                //    }
                //}
                string ss = UserInfoView.viewModel.LoginName;
                if (string.IsNullOrEmpty(UserInfoView.viewModel.LoginName))
                {
                    Growl.Warning("未登录");
                    TextBoxLog.AddLog("未登录");
                    AddTempTextErr("登录", new string[] { "未登录" + DateTime.Now.ToString() });
                    return;
                }
                if (buttno && butthave)
                {
                    Growl.Warning("产品类型异常");
                    TextBoxLog.AddLog("产品类型异常");
                    AddTempTextErr("产品类型", new string[] { "产品类型异常" + DateTime.Now.ToString() });
                    return;
                }
                if (!buttno&&!butthave)
                {
                    Growl.Warning("未选择产品类型");
                    TextBoxLog.AddLog("请选择产品类型，再启动初始化");
                    AddTempTextErr("产品类型", new string[] { "未选择产品类型" + DateTime.Now.ToString() });
                    return;
                }
                if (butthave)
                {
                    type = "F9920LV";
                }
                else
                {
                    type = "F9920LU";
                }
                if (!MainWindow2.viewModel.Vision|| !MainWindow2.viewModel.Electrical || !MainWindow2.viewModel.Toggle || !MainWindow2.viewModel.Test)
                {
                    Growl.Warning("通信端口异常");
                    TextBoxLog.AddLog("请解决通信端口，再启动初始化");
                    AddTempTextErr("通信端口", new string[] { "通信端口异常" + DateTime.Now.ToString() });
                    return;
                }
                //ischange=false;
                //Working = true;
                While.Wait(cancellationToken.Token, manualReset);
                //Growl.Info("准备放产品");
                //woekt[0] = Task.Run(() => starding());
                string retul = "";

                TextBoxLog.AddLog("初始化开始");
                retul = Statedetection();//是否需要初始化
                if (retul != "OK")
                {
                    ///如果位虚按或通信失败的不能初始化
                    for (int i = 0; i < 4; i++)
                    {
                        if (textnum[i] != 1 && textnum[i] != 0)
                        {
                            TextBoxLog.AddLog(retul);
                            return;
                        }
                    }
                    retul = zation();//旋转两次是为了保证两侧的旋转到位正常
                    if (retul != "OK")
                    {
                        TextBoxLog.AddLog(retul);
                        TextBoxLog.AddLog("初始化失败");
                        Uistart("初始化失败");
                        return;
                    }
                    retul = Statedetection();//初始化是否成功
                    if (retul != "OK")
                    {
                        TextBoxLog.AddLog(retul);
                        return;
                    }
                }
                //retul = Statedetection();//初始化是否成功
                //if (retul != "OK")
                //{
                //    TextBoxLog.AddLog(retul);
                //    return;
                //}
                if (direction != 1 && direction != 2)
                {
                    TextBoxLog.AddLog("转盘未到位");
                    return;
                }

                //retul = jinruqhuan();
                //if (retul != "OK")
                //{
                //    TextBoxLog.AddLog(retul);
                //    return;
                //}
                imgstart();
                TextBoxLog.AddLog("准备工作完成");
                Uistart("初始化成功");
                TextBoxLog.AddLog("开始生产");
                starding();
                //Task.WaitAll(woekt[0]);
                while (true)
                {
                    While.Wait(cancellationToken.Token, manualReset);
                    //string retul = "";
                    retul = rotate();
                    if (retul != "OK")
                    {
                        TextBoxLog.AddLog(retul);
                        continue;
                    }
                    directioning = true;
                    reach();
                    directioning = false;
                    Thread.Sleep(1);
                    UiChange();
                    //image.atob1();
                    imgchange();
                    Thread.Sleep(1);
                    var a = Task.Run(() =>
                     {
                         //if (error > 5)
                         //{
                         //    error = 0;
                         //    MessageBoxResult result = HandyControl.Controls.MessageBox.Show("连续失败多次确认产品型号是否正确？", null, MessageBoxButton.OKCancel, MessageBoxImage.None, MessageBoxResult.Cancel);
                         //}
                         artificial(0);
                         artificial(1);
                         if (RunState == RunState.Stop) { return; }
                         While.Wait(cancellationToken.Token, manualReset);
                         Changeled(0);
                         Changeled(1);
                         if (error > 5)
                         {
                             error = 0;
                             MessageBoxResult result = HandyControl.Controls.MessageBox.Show("连续失败多次确认产品型号是否正确？", null, MessageBoxButton.OKCancel, MessageBoxImage.None, MessageBoxResult.Cancel);
                         }
                         if (RunState == RunState.Stop) { return; }
                         While.Wait(cancellationToken.Token, manualReset);
                         BarChartViewNew.viewModel.UpdataData();
                         //if (error>5) {
                         //    error = 0;
                         //    MessageBoxResult result = HandyControl.Controls.MessageBox.Show("连续失败多次确认产品型号是否正确？", null, MessageBoxButton.OKCancel, MessageBoxImage.None, MessageBoxResult.Cancel);
                         //    //System.Console.WriteLine(result);
                         //    //if (result == MessageBoxResult.Cancel)
                         //    //{

                         //    //}
                         //}
                         Jack();
                         Changend();
                         if (RunState == RunState.Stop) { return; }
                         Task.WaitAll(woektasks);
                         //ischange=false;
                         starding();
                     });
                    var b = Task.Run(() =>
                    {
                        Task.WaitAll(woektasks);
                        JackUp();
                        //UiChange();
                        if (RunState == RunState.Stop) { return; }
                        While.Wait(cancellationToken.Token, manualReset);
                        if (butthave&&!buttno)
                        {
                            task1[0] = Task.Run(() => Suppress(0));
                            task1[1] = Task.Run(() => Suppress(1));
                            Task.WaitAll(task1);
                        }else if (!butthave && buttno)
                        {
                            task1[0] = Task.Run(() => Suppressno(0));
                            task1[1] = Task.Run(() => Suppressno(1));
                            Task.WaitAll(task1);
                        }
                        else
                        {
                            TextBoxLog.AddLog($"错误：产品型号异常");
                            return;
                        }
                        if (RunState == RunState.Stop) { return; }
                        While.Wait(cancellationToken.Token, manualReset);
                        JackD();
                        task4[0] = Task.Run(() => Vision(0));
                        task4[1] = Task.Run(() => Vision(1));
                        Task.WaitAll(task4);
                    });

                    Task.WaitAll(a, b);
                }
            }
            catch (OperationCanceledException)
            {
                TextBoxLog.AddLog("已停止，主流程");
            }
            catch (Exception ex)
            {
                TextBoxLog.AddLog($"错误：{ex.ToString()}");
                Logs.Write($"错误：{ex.ToString()}", LogsType.Err);
            }
            finally
            {
                cancellationToken?.Cancel();
                type = "";
                //Stop();
                Working = false;
                TextBoxLog.AddLog("已停止：全部");
                iscolll = true;
                RunState = RunState.Stop;
                //cancellationToken?.Cancel();
            }
        }

        private void artificial(int v)
        {
            int vnum;
            if (direction == 1)
            {
                vnum = v;
            }
            else
            {
                vnum = 2 + v;
            }
            if (!textokng[vnum].Contains("no") && textokng[vnum] != "okend")
            {
                string[] mvg = textokng[vnum].Split(':');
                if (mvg[0]== "页面7失败")
                {
                    MessageBoxResult result = HandyControl.Controls.MessageBox.Show((vnum+1)+"号测试位视觉测试失败,确认是否为不合格产品", null, MessageBoxButton.OKCancel, MessageBoxImage.None, MessageBoxResult.Cancel);
                    if (result == MessageBoxResult.Cancel)
                    {
                        textokng[vnum] = "okend";
                        textend[vnum] = "人工确认为合格";
                        PeopleUiupnew(v);
                    }
                    else
                    {
                        textend[vnum] = "人工确认为不合格";
                    }
                }
                else
                {
                    return;
                }
            }
            else
            {
                return;
            }
        }

        private string jinruqhuan()
        {
            string retul = "";
            string retulmsg = "";
            for (int i = 0; i < 4; i++)
            {
                var sto = LocalStatic.Test[i].ReadOn();
                if (!sto.IsSucceed)
                {
                    sto = LocalStatic.Test[i].ReadOn();
                    if (!sto.IsSucceed)
                    {

                        retulmsg = retulmsg+(i + 1) + "号测试位继电器准备失败\r\n";
                    }
                    else
                    {
                        TextBoxLog.AddLog((i + 1) + "号测试位继电器准备成功");
                    }
                }
                else
                {

                    TextBoxLog.AddLog((i + 1) + "号测试位继电器准备成功");
                }
            }
            Thread.Sleep(50);
            for (int i=0;i<4;i++)
            {
                retul = getvision1("进入模式", i);
                if (retul != "OK")
                {
                    retul = getvision1("进入模式", i);
                    if (retul != "OK")
                    {

                        retulmsg = retulmsg+(i+1) + "号测试位进入切换模式失败\r\n";
                    }
                    else
                    {
                        TextBoxLog.AddLog((i + 1) + "号测试位进入切换模式成功");
                    }
                }
                else
                {
                    TextBoxLog.AddLog((i + 1) + "号测试位进入切换模式成功");
                }
            }
            if (retulmsg!="")
            {
                return retulmsg;
            }
            return "OK";
        }

        /// <summary>
        /// 状态检测
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private string Statedetection()
        {
            try
            {
                string retul = "";
                int number = 0;
                int dian = 0;
                retul = getjack();
                if (retul != "OK")
                {
                    return retul;
                }
                TextBoxLog.AddLog("测试位状态检测通过");
                retul = prepose();
                if (retul != "OK")
                {
                    Growl.Error(retul);
                    return retul;
                }
                TextBoxLog.AddLog("气缸状态检测通过");
                while (true)
                {
                    Thread.Sleep(100);
                    number = number + 1;
                    if (number > 5)
                    {
                        break;

                    }
                    dian = getfreque();
                    if (dian != -1)
                    {
                        break;
                    }
                }
                if (dian == -1)
                {

                    retul = "旋转气缸到位通信失败";
                    return retul;
                }
                if (dian == 0)
                {

                    retul = "旋转气缸未就位";
                    return retul;
                }
                if (dian == 3)
                {

                    retul = "旋转气缸收到多个方向到位信号";
                    return retul;
                }
                direction = dian;
                TextBoxLog.AddLog("转盘状态检测通过");
                return retul;
            }
            catch (Exception ee)
            {
                return "状态检测失败" + ee.ToString();
            }
        }


        /// <summary>
        /// 初始化
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private string zation()
        {
            try
            {
                directioning = false;
                //way = 1;
                direction = 1;//防止如果转盘未就位
                string retul = "";
                retul = satisfy();//顶升气缸下降，按压气缸上升
                if (retul != "OK")
                {
                    return retul;
                }
                //retul = prepose();//气缸是否可以选择
                //if (retul != "OK")
                //{
                //    return retul;
                //}
                //TextBoxLog.AddLog("转盘安全可转动");
                While.Wait(cancellationToken.Token, manualReset);
                retul = rotate();
                if (retul != "OK")
                {
                    return retul;
                }
                //retul = turn(0);//旋转
                //if (retul != "OK")
                //{
                //    return retul;
                //}
                directioning = true;
                TextBoxLog.AddLog("旋转");
                //Thread.Sleep(2000);
                reach();//3秒未到位则暂停
                directioning = false;
                TextBoxLog.AddLog("旋转到位");
                Changeled(0);
                Changeled(1);
                While.Wait(cancellationToken.Token, manualReset);
                Jack();//有料就顶升
                Changend();
                TextBoxLog.AddLog("确认外侧无料");
                //Thread.Sleep(1000);
                //retul = prepose();
                //if (retul != "OK")
                //{
                //    return retul;
                //}
                //TextBoxLog.AddLog("转盘安全可转动");
                While.Wait(cancellationToken.Token, manualReset);
                retul = rotate();
                if (retul != "OK")
                {
                    return retul;
                }
                directioning = true;
                TextBoxLog.AddLog("旋转");
                reach();
                directioning = false;
                TextBoxLog.AddLog("旋转到位");
                Changeled(0);
                Changeled(1);
                While.Wait(cancellationToken.Token, manualReset);
                Jack();
                Changend();
                TextBoxLog.AddLog("确认外侧无料");
                //retul = getjack();//料是否清完
                //if (retul != "OK")
                //{
                //    return retul;
                //}
                //TextBoxLog.AddLog("初始化完成");
                return "OK";
            }
            catch (Exception ee)
            {
                return ee.ToString();
            }
        }

        //private void Updata()
        //{
        //    for (int i = 0; i < 4; i++) {
        //        if (textokng[i] == "okend") {
        //            BarChartView.viewModel.AddOk(i + 1);
        //        }
        //        else if (textokng[i] == "no")
        //        {
        //            continue;
        //        }
        //        else
        //        {
        //            BarChartView.viewModel.AddNg(i + 1);
        //        }
        //    }
        //}

        private void Jack()
        {
            if (direction == 1)
            {
                if (textnum[0] != 1 && textnum[1] != 1)
                {
                    return;
                }
            } else if (direction == 2)
            {
                if (textnum[2] != 1 && textnum[3] != 1)
                {
                    return;
                }
            }
            var aaa = LocalStatic.Electric.Readsentrelay(500, PortModel.Jack, new List<int>(), LocalFile.Config.Address);
            if (!aaa.IsSucceed)
            {
                aaa = LocalStatic.Electric.Readsentrelay(500, PortModel.Jack, new List<int>(), LocalFile.Config.Address);
                if (!aaa.IsSucceed)
                {
                    TextBoxLog.AddLog("顶升气缸顶升失败" + aaa.Err);
                    Stop();
                    return;
                }
            }
            Thread.Sleep(1000);
            aaa = LocalStatic.Electric.Readsentrelay(500, new List<int>(), PortModel.Jack, LocalFile.Config.Address);
            if (!aaa.IsSucceed)
            {
                LocalStatic.Electric.Readsentrelay(500, new List<int>(), PortModel.Jack, LocalFile.Config.Address);
                if (!aaa.IsSucceed)
                {
                    TextBoxLog.AddLog("顶升气缸下降失败" + aaa.Err);
                    Stop();
                    return;
                }
            }
            TextBoxLog.AddLog("请取料");
        }
        private void JackUp()
        {
            if (direction == 2)
            {
                if (textnum[0] != 1 && textnum[1] != 1)
                {
                    return;
                }
            }
            else if (direction == 1)
            {
                if (textnum[2] != 1 && textnum[3] != 1)
                {
                    return;
                }
            }
            var aaa = LocalStatic.Electric.Readsentrelay(500, PortModel.Suppress, new List<int>(), LocalFile.Config.Address);
            if (!aaa.IsSucceed)
            {
                aaa = LocalStatic.Electric.Readsentrelay(500, PortModel.Suppress, new List<int>(), LocalFile.Config.Address);
                if (!aaa.IsSucceed)
                {
                    TextBoxLog.AddLog($"按压气缸按压通信失败\r\n");
                    Stop();
                    return;
                }
            }
            TextBoxLog.AddLog("请取料");
        }
        private void JackD()
        {
            var aaa = LocalStatic.Electric.Readsentrelay(500, new List<int>(), PortModel.Suppress, LocalFile.Config.Address);
            if (!aaa.IsSucceed)
            {
                aaa = LocalStatic.Electric.Readsentrelay(500, new List<int>(), PortModel.Suppress, LocalFile.Config.Address);
                if (!aaa.IsSucceed)
                {
                    TextBoxLog.AddLog($"按压气缸上升通信失败\r\n");
                    Stop();
                    return;
                }
            }
        }
        /// <summary>
        /// 是否点击启动和开始测试第一部分
        /// </summary>
        private void starding()
        {
            runstart = 0;
            Working = false;
            Growl.Info("准备放产品");
            //TextBoxLog.AddLog("准备放产品");
            while (true)
            {
                Thread.Sleep(200);
                if (RunState == RunState.Stop) { return; }
                While.Wait(cancellationToken.Token, manualReset);
                string retul = "";
                if (runstart == 0)
                {
                    continue;
                }
                retul = obtain();
                //SetUi();
                runstart = 0;
                if (retul != "OK")
                {
                    TextBoxLog.AddLog(retul);
                    Growl.Warning(retul);
                    //Uiupnew(0, "待测");
                    //Uiupnew(1, "待测");
                    continue;
                }

                //if (direction == 1)
                //{
                //    Uiupnew(0, "待测");
                //    Uiupnew(1, "待测");
                //}
                //else
                //{
                //    Uiupnew(2, "待测");
                //    Uiupnew(3, "待测");
                //}
                //DoWork(0);
                //double getnumber = 0;

                //if (textnum[0] == 1)
                //{
                //    textokng[0] = "ok";
                //    Uiupnew(0, "电气");
                //}
                //if (textnum[1] == 1)
                //{
                //    textokng[1] = "ok";
                //    Uiupnew(1, "电气");
                //}

                woektasks[0] = Task.Run(() => DoWork(0));
                woektasks[1] = Task.Run(() => DoWork(1));
                TextBoxLog.AddLog("开始测试");
                Working = true;
                return;
            }
        }

        /// <summary>
        /// 是否按下气缸，按下的气缸是否顶住
        /// </summary>
        /// <returns></returns>
        private string ready()
        {
            if (direction == 1)
            {
                if (!cylinder) {
                    var ss = LocalStatic.Electric.Readsent(500, "");
                    if (ss.Value == "")
                    {
                        cylinder = true;
                    }
                    else
                    {
                        return "未检测下压";
                    }
                }

            }
            return "OK";
        }
        /// <summary>
        ///按压通断检测有按钮
        /// </summary>
        /// <param name="v"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Suppress(int v)
        {
            int vum;
            if (direction == 2)
            {
                vum = v;
            }
            else
            {
                vum = 2 + v;
            }
            if (textokng[vum] == ("ok"))
            {
                Uiupnew(vum, "按钮");
            }
            else
            {
                Uiupnew(vum, "按钮");
                return;
            }
            try
            {
                string okng = "ng";
                int number = 0;

                if (textokng[vum] != ("ok") || textokng[vum] == ("no") || textnum[vum] != 1)
                {
                    return;
                }
                //if (textnum[0 + v] == 1)
                //{
                //var aaa = LocalStatic.Electric.Readsentrelay(500, PortModel.Suppress, new List<int>(), LocalFile.Config.Address);
                //if (!aaa.IsSucceed)
                //{
                //    aaa = LocalStatic.Electric.Readsentrelay(500, PortModel.Suppress, new List<int>(), LocalFile.Config.Address);
                //    if (!aaa.IsSucceed)
                //    {
                //        TextBoxLog.AddLog($"按压气缸成功按压\r\n");

                //        Stop();
                //        return;
                //    }
                //}
                var s1 = new Result<string>();
                number = 0;
                while (okng != "ok")
                {
                    string restul = "";
                    //okng = "";
                    number = number + 1;
                    if (number > LocalFile.Config.number1)
                    {
                        break;
                    }

                    if (RunState == RunState.Stop) { return; }
                    While.Wait(cancellationToken.Token, manualReset);
                    s1 = LocalStatic.Test[vum].ReadOnoff();
                    if (s1.IsSucceed)
                    {
                        string[] msg = s1.Value.Split(' ');
                        if (int.Parse(msg[0]) > LocalFile.Config.buttUGND || int.Parse(msg[0]) < LocalFile.Config.buttDGND)
                        {
                            restul = restul + "按压通断GND超出范围";
                        }
                        if (int.Parse(msg[4]) > LocalFile.Config.buttUSW || int.Parse(msg[4]) < LocalFile.Config.buttDSW)
                        {
                            restul = restul + "按压通断SW超出范围";
                        }
                        if (restul == "")
                        {
                            restul = "ok";
                        }
                        else
                        {
                            restul = "按钮通断失败:" + restul;
                        }
                    }
                    else
                    {
                        restul = "按钮通断失败:通信失败";
                    }
                    okng = restul;
                }
                textokng[vum] = okng;
                if (okng != "ok")
                {
                    TextBoxLog.AddLog((vum + 1) + "号测试位按压通断失败"+ number);
                    return;
                }
                TextBoxLog.AddLog((vum + 1) + "号测试位按压通断成功"+ number);
                //aaa = LocalStatic.Electric.Readsentrelay(500, new List<int>(), PortModel.Suppress, LocalFile.Config.Address);
                //if (!aaa.IsSucceed)
                //{
                //    aaa = LocalStatic.Electric.Readsentrelay(500, new List<int>(), PortModel.Suppress, LocalFile.Config.Address);
                //    if (!aaa.IsSucceed)
                //    {
                //        TextBoxLog.AddLog($"按压气缸成功断开\r\n");
                //        Stop();
                //        return;
                //    } 
                //}
                if (RunState == RunState.Stop) { return; }
                While.Wait(cancellationToken.Token, manualReset);
                s1 = LocalStatic.Test[vum].ReadCurrent();
                if (!s1.IsSucceed)
                {
                    TextBoxLog.AddLog((vum + 1) + "号测试位复电失败");
                }
            }
            finally {

                Uiupnew(vum, "视觉");
            }

        }
        /// <summary>
        ///按压通断检测无按钮
        /// </summary>
        /// <param name="v"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Suppressno(int v)
        {
            int vum;
            if (direction == 2)
            {
                vum = v;
            }
            else
            {
                vum = 2 + v;
            }
            if (textokng[vum] == ("ok"))
            {
                Uiupnew(vum, "按钮");
            }
            else
            {
                Uiupnew(vum, "按钮");
                return;
            }
            try
            {
                string okng = "ng";
                int number = 0;

                if (textokng[vum] != ("ok") || textokng[vum] == ("no") || textnum[vum] != 1)
                {
                    return;
                }
                //if (textnum[0 + v] == 1)
                //{
                //var aaa = LocalStatic.Electric.Readsentrelay(500, PortModel.Suppress, new List<int>(), LocalFile.Config.Address);
                //if (!aaa.IsSucceed)
                //{
                //    aaa = LocalStatic.Electric.Readsentrelay(500, PortModel.Suppress, new List<int>(), LocalFile.Config.Address);
                //    if (!aaa.IsSucceed)
                //    {
                //        TextBoxLog.AddLog($"按压气缸成功按压\r\n");

                //        Stop();
                //        return;
                //    }
                //}
                var s1 = new Result<string>();
                number = 0;
                while (okng != "ok")
                {
                    string restul = "";
                    //okng = "";
                    number = number + 1;
                    if (number > LocalFile.Config.number1)
                    {
                        break;
                    }

                    if (RunState == RunState.Stop) { return; }
                    While.Wait(cancellationToken.Token, manualReset);
                    s1 = LocalStatic.Test[vum].ReadOnoff();
                    if (s1.IsSucceed)
                    {
                        string[] msg = s1.Value.Split(' ');
                        if (int.Parse(msg[0]) > LocalFile.Config.UGND || int.Parse(msg[0]) < LocalFile.Config.DGND)
                        {
                            restul = restul + "按压通断GND超出范围";
                        }
                        if (int.Parse(msg[4]) > LocalFile.Config.USW || int.Parse(msg[4]) < LocalFile.Config.DSW)
                        {
                            restul = restul + "按压通断SW超出范围";
                        }
                        if (restul == "")
                        {
                            restul = "ok";
                        }
                        else
                        {
                            restul = "按钮通断失败:" + restul;
                        }
                    }
                    else
                    {
                        restul = "按钮通断失败:通信失败";
                    }
                    okng = restul;
                }
                textokng[vum] = okng;
                if (okng != "ok")
                {
                    TextBoxLog.AddLog((vum + 1) + "号测试位按压通断失败"+ number);
                    return;
                }
                TextBoxLog.AddLog((vum + 1) + "号测试位按压通断成功"+ number);
                //aaa = LocalStatic.Electric.Readsentrelay(500, new List<int>(), PortModel.Suppress, LocalFile.Config.Address);
                //if (!aaa.IsSucceed)
                //{
                //    aaa = LocalStatic.Electric.Readsentrelay(500, new List<int>(), PortModel.Suppress, LocalFile.Config.Address);
                //    if (!aaa.IsSucceed)
                //    {
                //        TextBoxLog.AddLog($"按压气缸成功断开\r\n");
                //        Stop();
                //        return;
                //    }
                //}
                if (RunState == RunState.Stop) { return; }
                While.Wait(cancellationToken.Token, manualReset);
                s1 = LocalStatic.Test[vum].ReadCurrent();
                if (!s1.IsSucceed)
                {
                    s1 = LocalStatic.Test[vum].ReadCurrent();
                    if (!s1.IsSucceed)
                    {
                        TextBoxLog.AddLog((vum + 1) + "号测试位复电失败");
                    }
                }
            }
            finally
            {

                Uiupnew(vum, "视觉");
            }

        }
        /// <summary>
        ///视觉检测
        /// </summary>
        /// <param name="v"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Vision(int v)
        {
            int vnm;//测试位
            if (direction == 2)
            {
                vnm = v;
            }
            else
            {
                vnm = v + 2;
            }

            if (textokng[vnm] == ("ok"))
            {
                Uiupnew(vnm, "视觉");
            }
            else
            {
                Uiupnew(vnm, "视觉");
                return;
            }
            try
            {
                var s1 = LocalStatic.Test[vnm].ReadOn();
                if (!s1.IsSucceed)
                {
                    s1 = LocalStatic.Test[vnm].ReadOn();
                    if (!s1.IsSucceed)
                    { TextBoxLog.AddLog((vnm + 1) + "号视觉闭合继电器失败");
                        textokng[vnm] = "视觉进入失败:闭合继电器失败";
                       return;
                    }
                }
                Thread.Sleep(200);
                string okng = "ng";//临时结果
                string retul = "";
                int numb = 0;//复测次数
                var result = new Result<string>();

                if (textnum[vnm] != 1)//无料
                {
                    return;
                }
                if (textokng[vnm] != ("ok"))//上一项是否合格（no代表未测，上面一个判断无料直接return）
                {
                    return;
                }
                TextBoxLog.AddLog((vnm + 1) + "号测试位进入闭合继电器成功"+numb);
                numb = 0;
                while (okng != "ok")
                {
                    //numb = numb + 1;
                    if (numb > visnum)
                    {
                        break;
                    }
                    if (RunState == RunState.Stop) { return; }
                    While.Wait(cancellationToken.Token, manualReset);
                    //var ss = getvision(v, PortModel.SAlocation1, PortModel.GAlocation1, PortModel.SBlocation1, PortModel.GBlocation1, PortModel.Vision1);
                    retul = getvision1("进入模式", vnm);
                    if (retul != "OK")
                    {
                        numb = numb + 1;
                        okng = "切换失败:" + retul;
                        //return;
                    }
                    else
                    {
                        okng = "ok";
                    }
                }
                textokng[vnm] = okng;
                if (okng != "ok")
                {
                    TextBoxLog.AddLog((vnm + 1) + "号测试位进入切换模式失败" + retul + numb);
                    return;
                }
                TextBoxLog.AddLog((vnm + 1) + "号测试位进入切换模式成功" + numb);
                okng = "ng";
                //numb = 0;
                while (okng != "ok")
                {
                    //numb = numb + 1;
                    if (numb > visnum)
                    {
                        break;
                    }
                    if (RunState == RunState.Stop) { return; }
                    While.Wait(cancellationToken.Token, manualReset);
                    //var ss = getvision(v, PortModel.SAlocation1, PortModel.GAlocation1, PortModel.SBlocation1, PortModel.GBlocation1, PortModel.Vision1);
                    retul = getvision1("页面1", vnm);
                    if (retul != "OK")
                    {
                        numb = numb + 1;
                        okng = "页面1失败:" + retul;
                    }
                    else
                    {
                        okng = "ok";
                    }
                }
                textokng[vnm] = okng;
                if (okng != "ok")
                {
                    TextBoxLog.AddLog((vnm + 1) + "号测试位页面1视觉检测失败" + retul + numb);
                    return;
                }
                TextBoxLog.AddLog((vnm + 1) + "号测试位页面1视觉检测成功"+numb);
                okng = "ng";
                //numb = 0;
                while (okng != "ok")
                {
                    //numb = numb + 1;
                    if (numb > visnum)
                    {
                        break;
                    }
                    if (RunState == RunState.Stop) { return; }
                    While.Wait(cancellationToken.Token, manualReset);
                    //var ss = getvision(v, PortModel.SAlocation1, PortModel.GAlocation1, PortModel.SBlocation1, PortModel.GBlocation1, PortModel.Vision1);
                    retul = getvision1("页面2", vnm);
                    if (retul != "OK")
                    {
                        numb = numb + 1;
                        okng = "页面2失败:" + retul;
                    }
                    else
                    {
                        okng = "ok";
                    }
                }
                textokng[vnm] = okng;
                if (okng != "ok")
                {
                    TextBoxLog.AddLog((vnm + 1) + "号测试位页面2视觉检测失败" + retul + numb);
                    return;
                }
                TextBoxLog.AddLog((vnm + 1) + "号测试位页面2视觉检测成功"+numb);
                okng = "ng";
                //numb = 0;
                while (okng != "ok")
                {
                    //numb = numb + 1;
                    if (numb > visnum)
                    {
                        break;
                    }
                    if (RunState == RunState.Stop) { return; }
                    While.Wait(cancellationToken.Token, manualReset);
                    //var ss = getvision(v, PortModel.SAlocation1, PortModel.GAlocation1, PortModel.SBlocation1, PortModel.GBlocation1, PortModel.Vision1);
                    retul = getvision1("页面3", vnm);
                    if (retul != "OK")
                    {
                        numb = numb + 1;
                        okng = "页面3失败:" + retul;
                    }
                    else
                    {
                        okng = "ok";
                    }
                }
                textokng[vnm] = okng;
                if (okng != "ok")
                {
                    TextBoxLog.AddLog((vnm + 1) + "号测试位页面3视觉检测失败" + retul + numb);
                    return;
                }
                TextBoxLog.AddLog((vnm + 1) + "号测试位页面3视觉检测成功"+numb);
                okng = "ng";
                //numb = 0;
                while (okng != "ok")
                {
                    //numb = numb + 1;
                    if (numb > visnum)
                    {
                        break;
                    }
                    if (RunState == RunState.Stop) { return; }
                    While.Wait(cancellationToken.Token, manualReset);
                    //var ss = getvision(v, PortModel.SAlocation1, PortModel.GAlocation1, PortModel.SBlocation1, PortModel.GBlocation1, PortModel.Vision1);
                    retul = getvision1("页面4", vnm);
                    if (retul != "OK")
                    {
                        numb = numb + 1;
                        okng = "页面4失败:" + retul;
                    }
                    else
                    {
                        okng = "ok";
                    }
                }
                textokng[vnm] = okng;
                if (okng != "ok")
                {
                    TextBoxLog.AddLog((vnm + 1) + "号测试位页面4视觉检测失败" + retul + numb);
                    return;
                }
                TextBoxLog.AddLog((vnm + 1) + "号测试位页面4视觉检测成功"+numb);
                okng = "ng";
                //numb = 0;
                while (okng != "ok")
                {
                    //numb = numb + 1;
                    if (numb > visnum)
                    {
                        break;
                    }
                    if (RunState == RunState.Stop) { return; }
                    While.Wait(cancellationToken.Token, manualReset);
                    //var ss = getvision(v, PortModel.SAlocation1, PortModel.GAlocation1, PortModel.SBlocation1, PortModel.GBlocation1, PortModel.Vision1);
                    retul = getvision1("页面5", vnm);
                    if (retul != "OK")
                    {
                        numb = numb + 1;
                        okng = "页面5失败:" + retul;
                    }
                    else
                    {
                        okng = "ok";
                    }
                }
                textokng[vnm] = okng;
                if (okng != "ok")
                {
                    TextBoxLog.AddLog((vnm + 1) + "号测试位页面5视觉检测失败" + retul + numb);
                    return;
                }
                TextBoxLog.AddLog((vnm + 1) + "号测试位页面5视觉检测成功"+numb);
                okng = "ng";
                //numb = 0;
                while (okng != "ok")
                {
                    //numb = numb + 1;
                    if (numb > visnum)
                    {
                        break;
                    }
                    if (RunState == RunState.Stop) { return; }
                    While.Wait(cancellationToken.Token, manualReset);
                    //var ss = getvision(v, PortModel.SAlocation1, PortModel.GAlocation1, PortModel.SBlocation1, PortModel.GBlocation1, PortModel.Vision1);
                    retul = getvision1("页面6", vnm);
                    if (retul != "OK")
                    {
                        numb = numb + 1;
                        okng = "页面6失败:" + retul;
                    }
                    else
                    {
                        okng = "ok";
                    }
                }
                textokng[vnm] = okng;
                if (okng != "ok")
                {
                    TextBoxLog.AddLog((vnm + 1) + "号测试位页面6视觉检测失败" + retul + numb);
                    return;
                }
                TextBoxLog.AddLog((vnm + 1) + "号测试位页面6视觉检测成功"+numb);
                okng = "ng";
                //numb = 0; 
                while (okng != "okend")
                {
                    //numb = numb + 1;
                    if (numb > visnum)
                    {
                        break;
                    }
                    if (RunState == RunState.Stop) { return; }
                    While.Wait(cancellationToken.Token, manualReset);
                    //var ss = getvision(v, PortModel.SAlocation1, PortModel.GAlocation1, PortModel.SBlocation1, PortModel.GBlocation1, PortModel.Vision1);
                    retul = getvision1("页面7", vnm);
                    if (retul != "OK")
                    {
                        numb = numb + 1;
                        okng = "页面7失败:" + retul;
                    }
                    else
                    {
                        okng = "okend";
                    }
                }
                textokng[vnm] = okng;
                if (okng != "okend")
                {
                    TextBoxLog.AddLog((vnm + 1) + "号测试位页面7视觉检测失败" + retul + numb);
                    return;
                }
                TextBoxLog.AddLog((vnm + 1) + "号测试位页面7视觉检测成功"+numb);
                //okng = "ng";
                //numb = 0;
            }
            finally
            {
                Uiupnew(vnm, "视觉");
                TextBoxLog.AddLog((vnm + 1) + "号测试位视觉检测结束");
                var s1 = LocalStatic.Test[vnm].Readoff();
                if (!s1.IsSucceed)
                {
                    s1 = LocalStatic.Test[vnm].Readoff();
                    if (!s1.IsSucceed)
                    {
                        TextBoxLog.AddLog((vnm + 1) + "号视觉断开继电器失败");
                    }
                }
            }
            //SetUi();
        }


        /// <summary>
        /// 页面切换加视觉判断
        /// </summary>
        /// <param name="msg">测试位+页面</param>
        /// <returns></returns>
        private string getvision1(string msg, int v)
        {
            var result = new Result<string>();//切换页面返回结果
            string getsen = "";//视觉返回结果
            string fangxiang = "";//方向左或右
            int ampip = 0;//安普板IP
            ChangeBan qhaun = LocalStatic.Change1;//切换页面的串口对象
            VisionBan Vision = LocalStatic.Vision2;//视觉对象
            if (v == 0) {
                qhaun = LocalStatic.Change1;
                Vision = LocalStatic.Vision2;
                ampip = LocalFile.Config.Amp1;
                fangxiang = "R";
            }
            else if (v == 1)
            {
                qhaun = LocalStatic.Change1;
                Vision = LocalStatic.Vision1;
                ampip = LocalFile.Config.Amp2;
                fangxiang = "L";
            }
            else if (v == 2)
            {
                qhaun = LocalStatic.Change2;
                Vision = LocalStatic.Vision2;
                ampip = LocalFile.Config.Amp3;
                fangxiang = "R";
            }
            else if (v == 3)
            {
                qhaun = LocalStatic.Change2;
                Vision = LocalStatic.Vision1;
                ampip = LocalFile.Config.Amp4;
                fangxiang = "L";
            }
            switch (msg)
            {
                case "进入模式":
                    //result = qhaun.Readsent1(2000, ampip);
                    //if (!result.IsSucceed)
                    //{
                    //    Thread.Sleep(50);
                    //}
                    result = qhaun.Readsent1(2000, ampip);
                    if (!result.IsSucceed)
                    {
                        return "进入切换页面模式失败" + result.Err;
                    }
                    break;
                case "页面1":
                    result = qhaun.Readsent3(2000, ampip);
                    if (!result.IsSucceed)
                    {
                        return "切换页面1失败" + result.Err;
                    }
                    getsen = Vision.SendMes(fangxiang + PortModel.Vision1);
                    if (getsen != fangxiang + "CH1;OK")
                    {
                        return "页面1视觉失败" + getsen;
                    }
                    break;
                case "页面2":
                    result = qhaun.Readsent4(2000, ampip);
                    if (!result.IsSucceed)
                    {
                        return "切换页面2失败" + result.Err;
                    }
                    getsen = Vision.SendMes(fangxiang + PortModel.Vision2);
                    if (getsen != fangxiang + "CH2;OK")
                    {
                        return "页面2视觉失败" + getsen;
                    }
                    break;
                case "页面3":
                    result = qhaun.Readsent5(2000, ampip);
                    if (!result.IsSucceed)
                    {
                        return "切换页面3失败" + result.Err;
                    }
                    getsen = Vision.SendMes(fangxiang + PortModel.Vision3);
                    if (getsen != fangxiang + "CH3;OK")
                    {
                        return "页面3视觉失败" + getsen;
                    }
                    break;
                case "页面4":
                    result = qhaun.Readsent6(2000, ampip);
                    if (!result.IsSucceed)
                    {
                        return "切换页面4失败" + result.Err;
                    }
                    getsen = Vision.SendMes(fangxiang + PortModel.Vision4);
                    if (getsen != fangxiang + "CH4;OK")
                    {
                        return "页面4视觉失败" + getsen;
                    }
                    break;
                case "页面5":
                    result = qhaun.Readsent7(2000, ampip);
                    if (!result.IsSucceed)
                    {
                        return "切换页面5失败" + result.Err;
                    }
                    getsen = Vision.SendMes(fangxiang + PortModel.Vision5);
                    if (getsen != fangxiang + "CH5;OK")
                    {
                        return "页面5视觉失败" + getsen;
                    }
                    break;
                case "页面6":
                    result = qhaun.Readsent8(2000, ampip);
                    if (!result.IsSucceed)
                    {
                        return "切换页面6失败" + result.Err;
                    }
                    getsen = Vision.SendMes(fangxiang + PortModel.Vision6);
                    if (getsen != fangxiang + "CH6;OK")
                    {
                        return "页面6视觉失败" + getsen;
                    }
                    break;
                case "页面7":
                    result = qhaun.Readsent9(2000, ampip);
                    if (!result.IsSucceed)
                    {
                        return "切换页面7失败" + result.Err;
                    }
                    getsen = Vision.SendMes(fangxiang + PortModel.Vision7);
                    if (getsen != fangxiang + "CH7;OK")
                    {
                        return "页面7视觉失败" + getsen;
                    }
                    break;
            }
            return "OK";
        }
        /// <summary>
        /// 换料废案
        /// </summary>
        /// <param name="v"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Change()
        {
            //if (direction == 1)
            //{
            //    if (textokng[0].Contains("ng") || textokng[0].Contains("NG"))
            //    {
            //        var dd = LocalStatic.Electric.Readsentled(500, PortModel.LED1ng, 1, LocalFile.Config.Address);
            //    }
            //    else if (textokng[0] == "ok11")
            //    {
            //        var dd = LocalStatic.Electric.Readsentled(500, PortModel.LED1ok, 1, LocalFile.Config.Address);
            //    }
            //    if (textokng[1].Contains("ng"))
            //    {
            //        var dd = LocalStatic.Electric.Readsentled(500, PortModel.LED2ng, 1, LocalFile.Config.Address);
            //    }
            //    else if (textokng[1] == "ok11")
            //    {
            //        var dd = LocalStatic.Electric.Readsentled(500, PortModel.LED2ok, 1, LocalFile.Config.Address);
            //    }
            //    var aaa = LocalStatic.Electric.Readsentrelay(500, PortModel.Jack, new List<int>(), LocalFile.Config.Address);
            //    Thread.Sleep(500);
            //    aaa = LocalStatic.Electric.Readsentrelay(500, new List<int>(), PortModel.Jack, LocalFile.Config.Address);
            //}
            //else
            //{
            //    if (textokng[2].Contains("ng") || textokng[2].Contains("NG"))
            //    {
            //        var dd = LocalStatic.Electric.Readsentled(500, PortModel.LED1ng, 1, LocalFile.Config.Address);
            //    }
            //    else if (textokng[2] == "ok11")
            //    {
            //        var dd = LocalStatic.Electric.Readsentled(500, PortModel.LED1ok, 1, LocalFile.Config.Address);
            //    }
            //    if (textokng[3].Contains("ng") || textokng[3].Contains("NG"))
            //    {
            //        var dd = LocalStatic.Electric.Readsentled(500, PortModel.LED2ng, 1, LocalFile.Config.Address);
            //    }
            //    else if (textokng[3] == "ok11")
            //    {
            //        var dd = LocalStatic.Electric.Readsentled(500, PortModel.LED2ok, 1, LocalFile.Config.Address);
            //    }
            //    var aaa = LocalStatic.Electric.Readsentrelay(500, PortModel.Jack, new List<int>(), LocalFile.Config.Address);
            //    Thread.Sleep(500);
            //    aaa = LocalStatic.Electric.Readsentrelay(500, new List<int>(), PortModel.Jack, LocalFile.Config.Address);
            //}
            //while (true)
            //{
            //    Thread.Sleep(500);
            //    While.Wait(cancellationToken.Token, manualReset);
            //    if (direction == 1)
            //    {
            //        if (textnum[0] == 1)
            //        {

            //            var dd = LocalStatic.Test[0].ReadSensor();
            //            if (dd.IsSucceed)
            //            {
            //                if (!dd.IsSucceed)
            //                {

            //                }
            //                else
            //                {
            //                    int getnumber = int.Parse(dd.Value);
            //                    if (getnumber < LocalFile.Config.DSensor[0])
            //                    {
            //                        textnum[0] = 1;
            //                    }
            //                    else if (getnumber > LocalFile.Config.USensor[0])
            //                    {
            //                        var dd1 = LocalStatic.Electric.Readsentled(500, PortModel.LED1ok, 0, LocalFile.Config.Address);
            //                        dd1 = LocalStatic.Electric.Readsentled(500, PortModel.LED1ng, 0, LocalFile.Config.Address);
            //                        if (dd1.IsSucceed)
            //                        {
            //                            textnum[0] = 0;
            //                            textokng[0] = "no";
            //                        }
            //                    }
            //                    else
            //                    {
            //                        textnum[0] = 2;

            //                    }
            //                }
            //            }
            //        }
            //        if (textnum[1] == 1)
            //        {

            //            var dd = LocalStatic.Test[1].ReadSensor();
            //            if (dd.IsSucceed)
            //            {
            //                if (!dd.IsSucceed)
            //                {

            //                }
            //                else
            //                {
            //                    int getnumber = int.Parse(dd.Value);
            //                    if (getnumber < LocalFile.Config.DSensor[1])
            //                    {
            //                        textnum[1] = 1;
            //                    }
            //                    else if (getnumber > LocalFile.Config.USensor[1])
            //                    {
            //                        var dd1 = LocalStatic.Electric.Readsentled(500, PortModel.LED2ok, 0, LocalFile.Config.Address);
            //                        dd1 = LocalStatic.Electric.Readsentled(500, PortModel.LED2ng, 0, LocalFile.Config.Address);
            //                        if (dd1.IsSucceed)
            //                        {
            //                            textnum[1] = 0;
            //                            textokng[1] = "no";
            //                        }
            //                    }
            //                    else
            //                    {
            //                        textnum[1] = 2;

            //                    }
            //                }

            //            }
            //        }
            //        if (textnum[0] == 0 && textnum[1] == 0)
            //        {
            //            return;
            //        }
            //    }
            //    else
            //    {
            //        if (textnum[2] == 1)
            //        {

            //            var dd = LocalStatic.Test[2].ReadSensor();
            //            if (!dd.IsSucceed)
            //            {

            //            }
            //            else
            //            {
            //                int getnumber = int.Parse(dd.Value);
            //                if (getnumber < LocalFile.Config.DSensor[2])
            //                {
            //                    textnum[2] = 1;
            //                }
            //                else if (getnumber > LocalFile.Config.USensor[2])
            //                {
            //                    textnum[2] = 0;
            //                    textokng[2] = "no";
            //                    var dd1 = LocalStatic.Electric.Readsentled(500, PortModel.LED1ok, 0, LocalFile.Config.Address);
            //                    dd1 = LocalStatic.Electric.Readsentled(500, PortModel.LED1ng, 0, LocalFile.Config.Address);
            //                }
            //                else
            //                {
            //                    textnum[2] = 2;

            //                }
            //            }
            //        }
            //        if (textnum[3] == 1)
            //        {

            //            var dd = LocalStatic.Test[3].ReadSensor();
            //            if (!dd.IsSucceed)
            //            {

            //            }
            //            else
            //            {
            //                int getnumber = int.Parse(dd.Value);
            //                if (getnumber < LocalFile.Config.DSensor[3])
            //                {
            //                    textnum[3] = 1;
            //                }
            //                else if (getnumber > LocalFile.Config.USensor[3])
            //                {
            //                    textnum[3] = 0;
            //                    textokng[3] = "no";
            //                    var dd1 = LocalStatic.Electric.Readsentled(500, PortModel.LED2ok, 0, LocalFile.Config.Address);
            //                    dd1 = LocalStatic.Electric.Readsentled(500, PortModel.LED2ng, 0, LocalFile.Config.Address);
            //                }
            //                else
            //                {
            //                    textnum[3] = 2;

            //                }
            //            }
            //        }
            //        if (textnum[2] == 0 && textnum[3] == 0)
            //        {
            //            return;
            //        }
            //    }
            //}
        }
        /// <summary>
        /// 换料new亮灯
        /// </summary>
        /// <param name="v"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Changeled(int v)
        {
            var dt = DateTime.Now;
            var data = new BoxInfo();
            string strFu = dt.ToString("yyyy-MM-dd HH:mm:ss");
            Root root = new Root();
            int led = 0;
            int vnum;
            string ngok = "";
            if (direction == 1)
            { vnum = v;
            }
            else
            {
                vnum = 2 + v;
            }
            if (textend[vnum]!="")
            {
                data.Artificial = textend[vnum];
            }
            if (!textokng[vnum].Contains("no") && textokng[vnum] != "okend")
            {
                ngok = "ng";
                data.Num = (vnum + 1) + "号测试位";
                data.State = textokng[vnum];
                data.IsOk = "不合格";
                data.Time = dt;
                data.Name = UserInfoView.viewModel.LoginName;
                data.Type = type;
                DataDb.dbBox.Insertable(data).ExecuteCommand();
                //BarChartView.viewModel.AddNg(vnum + 1);
                if (textokng[vnum].Contains("按钮通断失败"))
                {
                    error = error + 1;
                }else
                {
                    error = 0;
                }
                if (LocalFile.Config.IsMESjoggle) {

                    root.testPerson = UserInfoView.viewModel.LoginName;
                    root.testResult = "失败";
                    root.testTime = strFu;
                    root.productModel = type;
                    string money = postmes(root);
                    while (money != "OK")
                    {
                        TextBoxLog.AddLog("MES上传失败");
                        money = postmes(root);
                    }
                    TextBoxLog.AddLog("MES上传成功");
                }
            }
            else if (textokng[vnum] == "okend")
            {
                ngok = "ok";
                data.Num = (vnum + 1) + "号测试位";
                data.State = "";
                data.IsOk = "合格";
                data.Time = dt;
                data.Name = UserInfoView.viewModel.LoginName;
                data.Type = type;
                DataDb.dbBox.Insertable(data).ExecuteCommand();
                //BarChartView.viewModel.AddOk(vnum + 1);
                error = 0;
                if (LocalFile.Config.IsMESjoggle)
                {
                    root.testPerson = UserInfoView.viewModel.LoginName;
                    root.testResult = "成功";
                    root.testTime = strFu;
                    root.productModel = type;
                    string money = postmes(root);
                    while (money != "OK")
                    {
                        TextBoxLog.AddLog("MES上传失败");
                        money = postmes(root);
                    }
                    TextBoxLog.AddLog("MES上传成功");
                }
            }

            if (v == 0)
            {
                if (ngok == "ok")
                {
                    led = PortModel.LED1ok;
                }
                else if (ngok == "ng")
                {
                    led = PortModel.LED1ng;
                }
            }
            else
            {
                if (ngok == "ok")
                {
                    led = PortModel.LED2ok;
                }
                else if (ngok == "ng")
                {
                    led = PortModel.LED2ng;
                }
            }
            if (ngok == "")
            {
                return;
            }
            var dd = LocalStatic.Electric.Readsentled(500, led, 1, LocalFile.Config.Address);
            if (!dd.IsSucceed)
            {
                TextBoxLog.AddLog("LED灯通信失败" + dd.Err);
                return;
            }

        }
        /// <summary>
        /// 换料new废案
        /// </summary>
        /// <param name="v"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Changeliao(int v)
        {
            //var qhuan = new Result<string>();

            //while (true)
            //{
            //    Thread.Sleep(200);
            //    if (RunState == RunState.Stop) {
            //        var dd1 = LocalStatic.Electric.Readsentled(500, PortModel.LED1ok, 0, LocalFile.Config.Address);
            //        dd1 = LocalStatic.Electric.Readsentled(500, PortModel.LED1ng, 0, LocalFile.Config.Address);
            //        dd1 = LocalStatic.Electric.Readsentled(500, PortModel.LED2ok, 0, LocalFile.Config.Address);
            //        dd1 = LocalStatic.Electric.Readsentled(500, PortModel.LED2ng, 0, LocalFile.Config.Address);
            //        return; }
            //    While.Wait(cancellationToken.Token, manualReset);
            //    if (direction == 1)
            //    {
            //        if (textnum[0 + v] != 0)
            //        {

            //            var dd = LocalStatic.Test[0 + v].ReadSensor();
            //            if (dd.IsSucceed)
            //            {
            //                if (!dd.IsSucceed)
            //                {

            //                }
            //                else
            //                {
            //                    int getnumber = int.Parse(dd.Value);
            //                    if (getnumber > LocalFile.Config.USensor[0 + v])
            //                    {
            //                        if (v == 0)
            //                        {
            //                            if (textokng[0 + v].Contains("ng") || textokng[0 + v].Contains("NG"))
            //                            {
            //                                qhuan = LocalStatic.Electric.Readsentled(500, PortModel.LED1ng, 0, LocalFile.Config.Address);
            //                            }
            //                            else
            //                            {
            //                                qhuan = LocalStatic.Electric.Readsentled(500, PortModel.LED1ok, 0, LocalFile.Config.Address);
            //                            }
            //                        }
            //                        else
            //                        {
            //                            if (textokng[0 + v].Contains("ng") || textokng[0 + v].Contains("NG"))
            //                            {
            //                                qhuan = LocalStatic.Electric.Readsentled(500, PortModel.LED2ng, 0, LocalFile.Config.Address);
            //                            }
            //                            else
            //                            {
            //                                qhuan = LocalStatic.Electric.Readsentled(500, PortModel.LED2ok, 0, LocalFile.Config.Address);
            //                            }
            //                        }
            //                        if (qhuan.IsSucceed)
            //                        {
            //                            textnum[0 + v] = 0;
            //                            textokng[0 + v] = "no";
            //                            return;
            //                        }
            //                    }
            //                }
            //            }
            //        }
            //    }
            //    else
            //    {
            //        if (textnum[2 + v] != 0)
            //        {

            //            var dd = LocalStatic.Test[2 + v].ReadSensor();
            //            if (!dd.IsSucceed)
            //            {

            //            }
            //            else
            //            {
            //                int getnumber = int.Parse(dd.Value);

            //                if (getnumber > LocalFile.Config.USensor[2 + v])
            //                {
            //                    if (v == 0)
            //                    {
            //                        if (textokng[2 + v].Contains("ng") || textokng[2 + v].Contains("NG"))
            //                        {
            //                            qhuan = LocalStatic.Electric.Readsentled(500, PortModel.LED1ng, 0, LocalFile.Config.Address);
            //                        }
            //                        else
            //                        {
            //                            qhuan = LocalStatic.Electric.Readsentled(500, PortModel.LED1ok, 0, LocalFile.Config.Address);
            //                        }
            //                    }
            //                    else
            //                    {
            //                        if (textokng[2 + v].Contains("ng") || textokng[2 + v].Contains("NG"))
            //                        {
            //                            qhuan = LocalStatic.Electric.Readsentled(500, PortModel.LED2ng, 0, LocalFile.Config.Address);
            //                        }
            //                        else
            //                        {
            //                            qhuan = LocalStatic.Electric.Readsentled(500, PortModel.LED2ok, 0, LocalFile.Config.Address);
            //                        }
            //                    }
            //                    if (qhuan.IsSucceed)
            //                    {
            //                        textnum[2 + v] = 0;
            //                        textokng[2 + v] = "no";
            //                        return;
            //                    }
            //                }
            //                else
            //                {


            //                }
            //            }
            //        }
            //    }
            //}
        }
        /// <summary>
        /// 换料最终
        /// </summary>
        /// <param name="v"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Changend()
        {
            var qhuan = new Result<string>();

            while (true)
            {
                Thread.Sleep(500); if (RunState == RunState.Stop) { return; }
                While.Wait(cancellationToken.Token, manualReset);
                if (direction == 1)
                {
                    if (textnum[0] == 0 && textnum[1] == 0)
                    {
                        return;
                    }
                    if (textnum[0] != 0)
                    {

                        var dd = LocalStatic.Test[0].ReadSensor();
                        if (dd.IsSucceed)
                        {

                            int getnumber = int.Parse(dd.Value);
                            if (getnumber > LocalFile.Config.USensor[0])
                            {
                                qhuan = LocalStatic.Electric.Readsentled(500, PortModel.LED1ng, 0, LocalFile.Config.Address);
                                qhuan = LocalStatic.Electric.Readsentled(500, PortModel.LED1ok, 0, LocalFile.Config.Address);
                                textnum[0] = 0;
                                textokng[0] = "no";
                                textend[0] = "";
                            }

                        }
                        else
                        {
                            TextBoxLog.AddLog($"1号测试板取料判断通信失败：{dd.Err}");
                        }
                    }
                    if (textnum[1] != 0)
                    {

                        var dd = LocalStatic.Test[1].ReadSensor();
                        if (dd.IsSucceed)
                        {

                            int getnumber = int.Parse(dd.Value);
                            if (getnumber > LocalFile.Config.USensor[1])
                            {
                                qhuan = LocalStatic.Electric.Readsentled(500, PortModel.LED2ng, 0, LocalFile.Config.Address);
                                qhuan = LocalStatic.Electric.Readsentled(500, PortModel.LED2ok, 0, LocalFile.Config.Address);
                                textnum[1] = 0;
                                textokng[1] = "no";
                                textend[1] = "";
                            }

                        }
                        else
                        {
                            TextBoxLog.AddLog($"2号测试板取料判断通信失败：{dd.Err}");
                        }
                    }
                }
                else
                {
                    if (textnum[2] == 0 && textnum[3] == 0)
                    {
                        return;
                    }
                    if (textnum[2] != 0)
                    {

                        var dd = LocalStatic.Test[2].ReadSensor();
                        if (dd.IsSucceed)
                        {

                            int getnumber = int.Parse(dd.Value);
                            if (getnumber > LocalFile.Config.USensor[2])
                            {
                                qhuan = LocalStatic.Electric.Readsentled(500, PortModel.LED1ng, 0, LocalFile.Config.Address);
                                qhuan = LocalStatic.Electric.Readsentled(500, PortModel.LED1ok, 0, LocalFile.Config.Address);
                                textnum[2] = 0;
                                textokng[2] = "no";
                                textend[2] = "";
                            }

                        }
                        else
                        {
                            TextBoxLog.AddLog($"3号测试板取料判断通信失败：{dd.Err}");
                        }
                    }
                    if (textnum[3] != 0)
                    {

                        var dd = LocalStatic.Test[3].ReadSensor();
                        if (dd.IsSucceed)
                        {

                            int getnumber = int.Parse(dd.Value);
                            if (getnumber > LocalFile.Config.USensor[3])
                            {

                                qhuan = LocalStatic.Electric.Readsentled(500, PortModel.LED2ng, 0, LocalFile.Config.Address);
                                qhuan = LocalStatic.Electric.Readsentled(500, PortModel.LED2ok, 0, LocalFile.Config.Address);

                                textnum[3] = 0;
                                textokng[3] = "no";
                                textend[3] = "";
                            }

                        }
                        else
                        {
                            TextBoxLog.AddLog($"4号测试板取料判断通信失败：{dd.Err}");
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 转盘是否到位
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private void reach()
        {
            int olddirection = direction;
            int i = 0;
            while (true)
            {
                i = i + 1;
                While.Wait(cancellationToken.Token, manualReset);
                if (!MainWindow2.viewModel.ischengg)
                {
                    direction = -1;
                    return;
                }
                //var de = LocalStatic.Electric.Readsentfrequency(500, PortModel.Accurate, LocalFile.Config.Address);
                string daow = MainWindow2.viewModel.msg[0] + " " + MainWindow2.viewModel.msg[1] + " ";
                if (daow == "00 01 " && olddirection != 2)
                {
                    direction = 2;
                    return;
                }
                else if (daow == "01 00 " && olddirection != 1)
                {

                    direction = 1;
                    return;
                }
                else if (daow == "00 00 ")
                {
                    direction = 0;
                }
                else
                {
                    direction = 3;
                }
                //if (de.IsSucceed)
                //{
                //    if (de.Value == "00 01 "&& olddirection!= 2)
                //    {
                //        direction = 2;
                //        return;
                //    }
                //    else if (de.Value == "01 00 " && olddirection != 1)
                //    {

                //        direction = 1;
                //        return;
                //    }
                //    else if (de.Value == "00 00 ")
                //    {
                //        direction = 0;
                //    }
                //    else
                //    {
                //        direction = 3;
                //    }


                //}
                if (i > 30)
                {
                    i = 0;
                    TextBoxLog.AddLog("转盘超时！暂停");
                    Pause();
                }
                Thread.Sleep(100);
            }
        }

        /// <summary>
        /// 在旋转时就开始测试
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void DoWork(int i)
        {
            int vum = 0;//测试位
            double getnumber = 0;
            if (direction == 1)
            {
                vum = i;
            }
            else
            {
                vum = i + 2;
            }
            if (textnum[vum] != 1)
            {
                return;
            }
            textokng[vum] = "ok";
            Uiupnew(vum, "电气");
            try
            {
                string okng = "ng";//临时结果
                int number = 0;//复测次数

                //var sto = LocalStatic.Test[vum].Readoff();
                //if (!sto.IsSucceed)
                //{
                //    TextBoxLog.AddLog((vum + 1) + "号测试位断开继电器失败");
                //}
                if (textnum[vum] == 1)
                {
                    var s1 = new Result<string>();
                    number = 0;
                    while (okng != "ok")
                    {
                        number = number + 1;
                        if (number > LocalFile.Config.number1)
                        {
                            break;
                        }
                        While.Wait(cancellationToken.Token, manualReset);

                        s1 = LocalStatic.Test[vum].ReadOnoff();
                        if (s1.IsSucceed)
                        {

                            string restul = judge(s1.Value);
                            //TextBoxLog.AddLog((vum) + "UA" + getnumber.ToString());
                            if (restul != "OK")
                            {
                                okng = "通断失败:" + restul;
                            }
                            else
                            {
                                okng = "ok";
                            }
                        }
                        else
                        {
                            okng = "通断失败:通信失败" + s1.Value;
                        }
                    }
                    //string reul = "";
                    //string[] msg = s1.Value.Split(' ');
                    //for (int s = 0; s < 8; s++)
                    //{
                    //    reul = reul + (s + 1) + "号通断：" + msg[s] + " ";
                    //}
                    //TextBoxLog.AddLog((vum+1) + $"号测试位通断 " + reul);
                    textokng[vum] = okng;
                    if (okng != "ok")
                    {
                        TextBoxLog.AddLog((vum + 1) + "号测试位通断测试失败"+number);
                        return;
                    }
                    okng = "ng";
                    TextBoxLog.AddLog((vum + 1) + "号测试位通断测试完成" + number);
                    number = 0;
                    while (okng != "ok")
                    {
                        number = number + 1;
                        if (number > LocalFile.Config.number2)
                        {
                            break;
                        }
                        While.Wait(cancellationToken.Token, manualReset);
                        s1 = LocalStatic.Test[vum].ReadFrequency();
                        if (s1.IsSucceed)
                        {
                            getnumber = double.Parse(s1.Value);

                            //TextBoxLog.AddLog((vum+1) + "号测试位HZ" + getnumber.ToString());
                            if (getnumber < LocalFile.Config.DHZ || getnumber > LocalFile.Config.UHZ)
                            {
                                okng = "频率失败:频率未在范围内";
                            }
                            else
                            {
                                okng = "ok";
                            }

                        }
                        else
                        {
                            okng = "频率失败:通信失败";
                        }
                    }
                    TextBoxLog.AddLog((vum + 1) + "号测试位频率" + (getnumber / 1000).ToString("F3") + "KHz");
                    textokng[vum] = okng;
                    if (okng != "ok")
                    {
                        TextBoxLog.AddLog((vum + 1) + "号测试位频率测试失败" + number);
                        return;
                    }
                    okng = "ng";
                    TextBoxLog.AddLog((vum + 1) + "号测试位频率测试完成" + number);
                    number = 0;
                    while (okng != "ok")
                    {
                        number = number + 1;
                        if (number > LocalFile.Config.number2)
                        {
                            break;
                        }
                        While.Wait(cancellationToken.Token, manualReset);
                        s1 = LocalStatic.Test[vum].ReadCurrent();
                        if (s1.IsSucceed)
                        {
                            getnumber = double.Parse(s1.Value);
                            if (getnumber < LocalFile.Config.DUA || getnumber > LocalFile.Config.UUA)
                            {
                                okng = "电流失败:未在范围内";
                            }
                            else
                            {
                                okng = "ok";
                            }
                        }
                        else
                        {
                            okng = "电流失败:通信失败";
                        }
                    }
                    TextBoxLog.AddLog((vum + 1) + "号测试位电流" + (getnumber / 100).ToString("F2") + "uA");
                    textokng[vum] = okng;
                    if (okng != "ok")
                    {
                        TextBoxLog.AddLog((vum + 1) + "号测试位电流测试失败" + number);
                        return;
                    }
                    okng = "ng";
                    TextBoxLog.AddLog((vum + 1) + "号测试位电流测试完成" + number);
                }
            }
            finally
            {
                //Uiupnew(vum, "电气");
            }
        }
        /// <summary>
        /// 通断检测
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private string judge(string value)
        {
            try
            {
                string[] msg = value.Split(' ');
                if (int.Parse(msg[0]) > LocalFile.Config.UGND || int.Parse(msg[0]) < LocalFile.Config.DGND)
                {
                    return "GND超出范围";
                }
                if (int.Parse(msg[1]) > LocalFile.Config.UVDD || int.Parse(msg[1]) < LocalFile.Config.DVDD)
                {
                    return "VDD超出范围";
                }
                if (int.Parse(msg[2]) > LocalFile.Config.UVCC || int.Parse(msg[2]) < LocalFile.Config.DVCC)
                {
                    return "VCC超出范围";
                }
                if (int.Parse(msg[3]) > LocalFile.Config.ULCDCLK || int.Parse(msg[3]) < LocalFile.Config.DLCDCLK)
                {
                    return "LCDCLK超出范围";
                }
                if (int.Parse(msg[4]) > LocalFile.Config.USW || int.Parse(msg[4]) < LocalFile.Config.DSW)
                {
                    return "SW超出范围";
                }
                if (int.Parse(msg[5]) > LocalFile.Config.ULCDDAT || int.Parse(msg[5]) < LocalFile.Config.DLCDDAT)
                {
                    return "LCDDAT超出范围";
                }
                if (int.Parse(msg[6]) > LocalFile.Config.UNON || int.Parse(msg[6]) < LocalFile.Config.DNON)
                {
                    return "NON超出范围";
                }
                if (int.Parse(msg[7]) > LocalFile.Config.ULCDSTB || int.Parse(msg[7]) < LocalFile.Config.DLCDSTB)
                {
                    return "LCDSTB超出范围";
                }
                return "OK";
            }
            catch (Exception ee)
            {
                return ee.ToString();
            }
        }

        /// <summary>
        /// 根据转盘方向反方向旋转
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private string rotate()
        {
            string retul = prepose();
            if (retul != "OK")
            {
                Growl.Error(retul);
                TextBoxLog.AddLog(retul);
                Stop();
                return retul;
            }
            if (direction == 1)
            {
                var ioi1 = LocalStatic.Electric.Readsentrelay(500, PortModel.Rotate1, PortModel.Rotate2, LocalFile.Config.Address);
                if (!ioi1.IsSucceed)
                {
                    return "气缸转动失败"+ioi1.Err;
                }
                way = 1;
                return "OK";
            }
            else if (direction == 2)
            {
                var ioi3 = LocalStatic.Electric.Readsentrelay(500, PortModel.Rotate2, PortModel.Rotate1, LocalFile.Config.Address);
                if (!ioi3.IsSucceed)
                {
                    return "气缸转动失败" + ioi3.Err;
                }
                way = 2;
                return "OK";
            }
            else
            {
                way = 0;
                return "转盘状态异常" + direction.ToString();
            }
        }
        /// <summary>
        /// 是否可以旋转
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private string prepose()
        {
            //var ioi = LocalStatic.Electric.Readsentfrequency(500, PortModel.EAll, LocalFile.Config.Address);
            //if (!ioi.IsSucceed)
            //{
            //    return "状态检测通信，长度错误"+ioi.Err;
            //}
            //else
            //{

            ;

            //var send = SetTrigger( LocalFile.Config.Address);
            //if (ioi.Value.Length != 42)
            //{
            //    return "状态检测通信，长度错误";
            //}
            if (!MainWindow2.viewModel.ischengg)
            {

                return "状态检测通信错误" + MainWindow2.viewModel.errtext;
            }
            if (MainWindow2.viewModel.msg[2] != "01")
            {
                return "左顶升下降未检测到位" + MainWindow2.viewModel.msg[2];
            }

            if (MainWindow2.viewModel.msg[3] != "00")
            {
                return "左顶升检测到顶升" + MainWindow2.viewModel.msg[3];
            }
            if (MainWindow2.viewModel.msg[4] != "01")
            {
                return "右顶升下降未检测到位" + MainWindow2.viewModel.msg[4];
            }
            if (MainWindow2.viewModel.msg[5] != "00")
            {
                return "右顶升检测到顶升" + MainWindow2.viewModel.msg[5];
            }

            if (MainWindow2.viewModel.msg[6] != "01")
            {
                return "开关箱报警";
            }
            if (MainWindow2.viewModel.msg[8] != "00")
            {
                return "急停按钮报警";
            }
            if (MainWindow2.viewModel.msg[9] != "00")
            {
                //return "光栅报警";
            }
            if (MainWindow2.viewModel.msg[10] != "01")
            {
                return "右按压气缸未上升";
            }
            if (MainWindow2.viewModel.msg[11] != "00")
            {
                return "右按压气缸下降";
            }
            if (MainWindow2.viewModel.msg[12] != "01")
            {
                return "左按压气缸未上升";
            }
            if (MainWindow2.viewModel.msg[13] != "00")
            {
                return "左按压气缸下降";
            }
            return "OK";
        } 
        /// <summary>
        /// 旋转
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private string turn(int v)
        {
            var ioi = new Result<string>();
            if (v == 1)
            {
                ioi = LocalStatic.Electric.Readsentrelay(500, PortModel.Rotate2, PortModel.Rotate1, LocalFile.Config.Address);
            }
            else
            {
                ioi = LocalStatic.Electric.Readsentrelay(500, PortModel.Rotate1, PortModel.Rotate2, LocalFile.Config.Address);
            }
            
            if (!ioi.IsSucceed)
            {
                return "旋转失败"+ioi.Err;
            }
            return "OK";
        }

        /// <summary>
        /// 顶起和按压断开
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private string satisfy()
        {
            var ioi = LocalStatic.Electric.Readsentrelay(500, new List<int>(), PortModel.Jack, LocalFile.Config.Address);
            if (!ioi.IsSucceed)
            {
                return "顶升气缸下降通信失败"+ioi.Err;
            }
            ioi = LocalStatic.Electric.Readsentrelay(500, new List<int>(), PortModel.Suppress, LocalFile.Config.Address);
            if (!ioi.IsSucceed)
            {
                return "按压气缸上升通信失败" + ioi.Err;
            }

            return "OK";
        }
        /// <summary>
        /// 串口通信强制启动还是正常启动
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private string obtain()
        {
            string retulmas = "";
            int getnumber = 0;
            var ioi1 = new Result<string>();
            int vum = 0;
            //var ioi11 = LocalStatic.Electric.Readsent(500,"");
            if (direction == 1)
            {
                vum = 0;
            }
            else
            {
                vum = 2;
            }
            if (LocalFile.Config.Block[vum])
            {
                textnum[vum] = 0;
            }
            else
            {
                ioi1 = LocalStatic.Test[vum].ReadSensor();
                if (!ioi1.IsSucceed)
                {
                    Thread.Sleep(100);
                    ioi1 = LocalStatic.Test[vum].ReadSensor(); 
                    if (!ioi1.IsSucceed)
                    {
                        retulmas = retulmas + (vum + 1).ToString() + "号测试位通信失败！\r\n";
                    }
                }
                else
                {
                    getnumber = int.Parse(ioi1.Value);
                    if (getnumber < LocalFile.Config.DSensor[vum])
                    {
                        textnum[vum] = 1;
                    }
                    else if (getnumber > LocalFile.Config.USensor[vum])
                    {
                        textnum[vum] = 0;
                    }
                    else
                    {
                        textnum[vum] = 2;
                        retulmas = retulmas + (vum + 1).ToString() + "号测试位未按压到位或方向错误请按压或拿开！"  + "\r\n";
                    }
                }
            }
            if (LocalFile.Config.Block[vum + 1])
            {
                textnum[vum + 1] = 0;
            }
            else
            {
                ioi1 = LocalStatic.Test[vum + 1].ReadSensor();
                if (!ioi1.IsSucceed)
                {
                    Thread.Sleep(100);
                    ioi1 = LocalStatic.Test[vum + 1].ReadSensor();
                    if (!ioi1.IsSucceed)
                    {
                        retulmas = retulmas + (vum + 2).ToString() + "号测试位通信失败！" + "\r\n";
                    }
                }
                else
                {
                    getnumber = int.Parse(ioi1.Value);
                    if (getnumber < LocalFile.Config.DSensor[vum + 1])
                    {
                        textnum[vum + 1] = 1;
                    }
                    else if (getnumber > LocalFile.Config.USensor[vum + 1])
                    {
                        textnum[vum + 1] = 0;
                    }
                    else
                    {
                        textnum[vum + 1] = 2;
                        retulmas = retulmas + (vum + 2).ToString() + "号测试位未按压到位或方向错误请按压或拿开！"  + "\r\n";
                    }
                }
            }

            if (retulmas != "")
            {
                return retulmas;
            }
            //是否强制启动
            if (runstart == 1)
            {
                //正常启动启动判断是否满足条件
                //if (direction == 1)
                //{
                if (textnum[vum] != 1 && !LocalFile.Config.Block[vum])
                {
                    retulmas = retulmas + (vum + 1).ToString() + "号位无料";
                }
                if (textnum[vum + 1] != 1 && !LocalFile.Config.Block[vum + 1])
                {
                    retulmas = retulmas + (vum + 2).ToString() + "号位无料";
                }
                if (retulmas != "")
                {
                    return retulmas;
                }
                return "OK";
                //}
                //else
                //{
                //    if (textnum[2] != 1)
                //    {
                //        retulmas = retulmas + "3号位无料";
                //    }
                //    if (textnum[3] != 1)
                //    {
                //        retulmas = retulmas + "4号位无料";
                //    }
                //    if (retulmas != "")
                //    {
                //        return retulmas;
                //    }
                //    return "OK";
                //}
            }
            else if (runstart == 2)
            {
                return "OK";
            }
            else
            {
                return "启动状态错误" + runstart;
            }
        }
        
        ///// <summary>
        /// 开始
        /// </summary>
        private void Start()
        {
            cancellationToken = new CancellationTokenSource();
            manualReset = new ManualResetEvent(true);
            //Task.Run(TaskAll);
            RunState = RunState.Run;
        }

        /// <summary>
        /// 暂停
        /// </summary>
        public void Pause()
        {
            manualReset.Reset();
            RunState = RunState.Pause;
        }

        /// <summary>
        /// 继续
        /// </summary>
        public void Continue()
        {
            manualReset.Set();
            RunState = RunState.Run;
        }

        /// <summary>
        /// 停止
        /// </summary>
        public void Stop()
        {
            cancellationToken?.Cancel();
            if (RunState == RunState.Pause)
            {
                manualReset.Set();
            }
            //RunState = RunState.Stop;
        }

        private void TaskAll()
        {

            try
            {
                Task.WaitAll(Task1(), Task2());
            }
            catch (Exception ex)
            {
                TextBoxLog.AddLog($"错误：{ex.ToString()}");
            }
            finally
            {
                Stop();
                TextBoxLog.AddLog("已停止：全部");
            }
        }

        private async Task Task1()
        {
            try
            {
                for (int i = 0; true; i++)
                {
                    await Task.Delay(500);
                    //监听：开始、暂停、停止
                    While.Wait(cancellationToken.Token, manualReset);

                    TextBoxLog.AddLog($"任务1：{i}");
                }
            }
            catch (OperationCanceledException)
            {
                TextBoxLog.AddLog("已停止1");
            }
            catch (Exception ex)
            {
                TextBoxLog.AddLog($"错误：{ex.ToString()}");
            }
            finally
            {
                cancellationToken?.Cancel();
            }
        }

        private async Task Task2()
        {
            try
            {
                for (int i = 0; true; i++)
                {
                    await Task.Delay(500);
                    //监听：开始、暂停、停止
                    While.Wait(cancellationToken.Token, manualReset);

                    TextBoxLog.AddLog($"任务2：{i}");
                }
            }
            catch (OperationCanceledException)
            {
                TextBoxLog.AddLog("已停止2");
            }
            catch (Exception ex)
            {
                TextBoxLog.AddLog($"错误：{ex.ToString()}");
            }
            finally
            {
                cancellationToken?.Cancel();
            }
        }
        #endregion
    }
}
